How to use driver.safeExecuteAsync method in Appium

Best JavaScript code snippet using appium

Run Appium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

edge.js

Source: edge.js Github

copy
1// https://www.selenium.dev/documentation/legacy/json_wire_protocol/
2// https://github.com/admc/wd/blob/master/lib/main.js
3
4import wd from 'wd';
5import chai from 'chai';
6import chaiAsPromised from 'chai-as-promised';
7
8function formatXml(xml, tab) { // tab = optional indent value, default is tab (\t)
9  var formatted = '', indent= '';
10  tab = tab || '\t';
11  xml.split(/>\s*</).forEach(function(node) {
12      if (node.match( /^\/\w/ )) indent = indent.substring(tab.length); // decrease indent by one 'tab'
13      formatted += indent + '<' + node + '>\r\n';
14      if (node.match( /^<?\w[^>]*[^\/]$/ )) indent += tab;              // increase indent
15  });
16  return formatted.substring(1, formatted.length-3);
17}
18
19// import * as cv from 'opencv-bindings'
20// Define a global variable 'Module' with a method 'onRuntimeInitialized':
21// let Module = {
22//   onRuntimeInitialized() {
23//     // this is our application:
24//     console.log(cv.getBuildInformation())
25//   }
26// }
27// Load 'opencv.js' assigning the value to the global variable 'cv'
28
29// cv = require('../opencv.js')
30
31// import { startServer } from 'appium-windows-driver/lib/server.js';
32// import { isAdmin } from 'appium-windows-driver/lib/installer.js';
33// import { /*driver,*/ By2, /* windowsAppDriverCapabilities*/ } from 'selenium-appium'
34
35chai.should();
36chai.use(chaiAsPromised);
37
38const TEST_PORT = 4723//4788;
39const TEST_HOST = 'localhost';
40
41
42var browser = wd.remote();
43
44// optional extra logging
45browser.on('status', function(info) {
46  console.log(info.cyan);
47});
48browser.on('command', function(eventType, command, response) {
49  console.log(' > ' + eventType.cyan, command, (response || '').grey);
50});
51browser.on('http', function(meth, path, data) {
52  console.log(' > ' + meth.magenta, path, (data || '').grey);
53});
54
55
56// async function getCalculatorResultText() {
57//   const text = await By2.nativeAccessibilityId('CalculatorResults').getText();
58//   return text.replace('Display is', '').trim();
59// }
60
61// function getAllMethods(obj = this) {
62//           return Object.keys(obj)
63//               .filter((key) => typeof obj[key] === 'function')
64//               .map((key) => obj[key]);
65//       }
66
67
68describe('edge se lance', async function () {
69  this.timeout(100000)
70  // if (!await isAdmin()) {
71  //   return;
72  // }
73
74  // let server;
75  let driver;
76
77  before(async function () {
78    // server = await startServer(TEST_PORT, TEST_HOST);
79    // console.log("server ok", server)
80  });
81
82  // after(async function () {
83  //   if (server) {
84  //     await server.close();
85  //   }
86  //   server = null;
87  // });
88
89  beforeEach(function () {
90    // if (server) {
91      driver = wd.promiseChainRemote(TEST_HOST, TEST_PORT);
92    // }
93  });
94
95  afterEach(async function () {
96  //  console.log("afterEach")
97    if (driver) {
98      await driver.quit();
99    }
100    driver = null;
101  });
102
103  it('should run a basic session using a real client', async function () {
104    await driver.init({
105      app: "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
106      platformName: 'Windows',
107    });
108
109    //DRIVER
110   console.log(driver)
111
112
113//ELEMENTS
114await driver.sleep(1000)
115
116// show elements
117// await elements(driver)
118
119//SOURCE
120// await xmlSource(driver)
121//
122// await driver.sleep(3000)
123
124let elements = await driver.elements("xpath",'//*')
125await driver.sleep(1000)
126 console.log(elements.length , " elements")
127console.log("use FOR await")
128 let indice = 0
129for await (const e of elements){
130  let el ={}
131  el.tagName = await e.getTagName()
132  el.text = await e.text()
133   //el.name = await e.getAttribute("name")
134   el.Name = await e.getAttribute("Name")
135   el.id = await e.getAttribute("id")
136   el.href = await e.getAttribute("href")
137   el.string = await e.toString()
138   el.json = await e.toJSON()
139   el.placeholder = await e.getAttribute("placeholder")
140  // let attrs = await driver.safeExecuteAsync("return arguments[0].attributes", e)
141
142  //console.log(s)
143  //console.log(indice, el.text, )
144  if (el.text != "Fermer" && el.text != "Réduire" && el.text != "Agrandir" && el.text != "Fermer l'onglet"){
145    try {
146      await e.click()
147      await e.sendKeys(indice)
148      await e.type(indice)
149    //
150console.log("-----------------",indice, el.Name,  el.text, " ok")
151if(indice == 21){
152  console.log(el)
153}
154    }
155    catch(e){
156      console.log(indice, el.text, " not", e)
157    }
158
159    indice ++
160  }
161  // if (el.text == "Nouvel Onglet"){
162  //   console.log("NOUVEAU")
163  //   await el.click()
164  // }
165//    if(el.text == "Entrez votre terme de recherche"){
166//      await el.type("hello world!")
167// // await element.type(Key.Enter)
168// console.log("saisie ok")
169//      await driver.sleep(1000)
170//    }
171}
172   console.log(elements.length , " elements")
173
174
175
176
177
178//await saisie(driver)
179// driver.settings({"getMatchedImageResult": true})
180// let test = await driver.element('-image', "C:\\Users\\psn\\dev\\appium\\monapp\\images\\jenkins.jpg" )
181// let b64 = test.getAttribute('visual')
182// console.log("b64",b64)
183//console.log("test jenkins",test)
184//await test.click()
185
186
187
188// let title = await driver.executeAsync('document.title')
189// //  let s = e.source()
190// console.log("title",title)
191// elements.forEach((e, i) => {
192//
193//   let tagName = await e.getTagName()
194//  // let t = await e.text()
195//  // let n = await e.getAttribute("name")
196//  //  let i_d = await e.getAttribute("id")
197//  //  console.log(i,t, n, i_d)
198//  console.log(i, tagName)
199// });
200
201// await driver.get("http://appium.io/")
202// it('Addition', async () => {
203  // Find the buttons by their names and click them in sequence to perform 1 + 7 = 8
204  //"/Pane[@ClassName=\"#32769\"][@Name=\"Bureau 1\"]/Window[@ClassName=\"ApplicationFrameWindow\"][@Name=\"Calculatrice\"]/Window[@ClassName=\"Windows.UI.Core.CoreWindow\"][@Name=\"Calculatrice\"]/Group[@ClassName=\"LandmarkTarget\"]/Group[@Name=\"Pavé numérique\"][@AutomationId=\"NumberPad\"]/Button[@Name=\"Sept\"][@AutomationId=\"num7Button\"]"
205
206//  await driver.elementByAccessibilityId("num7Button").click()
207//  await driver.elementByAccessibilityId("num9Button").click()
208//  await driver.elementByAccessibilityId("num9Button").click()
209//  await driver.elementByAccessibilityId("multiplyButton").click()
210//  await driver.elementByAccessibilityId("num4Button").click()
211//  await driver.elementByAccessibilityId("num5Button").click()
212//  await driver.elementByAccessibilityId("num9Button").click()
213 // await driver.elementByAccessibilityId("view_").click()
214// await driver.sleep(3000)
215//  await driver.elementByAccessibilityId("clearEntryButton").click()
216await driver.sleep(3000)
217
218
219  // await By2.nativeName('One').click();
220  // await By2.nativeName('Plus').click();
221  // await By2.nativeName('Seven').click();
222  // await By2.nativeName('Equals').click();
223  // expect(await getCalculatorResultText()).toBe('8');
224// });
225
226  });
227});
228
229
230async function xmlSource(driver){
231  let source = await driver.source()
232  console.log("source", formatXml(source))
233  let elementsXml = formatXml(source).split('\n')
234  console.log(elementsXml)
235}
236
237
238async function elements(driver){
239  let elements = await driver.elements("xpath",'//*')
240  await driver.sleep(1000)
241   console.log(elements.length , " elements")
242  console.log("use FOR await")
243   let indice = 0
244  for await (const e of elements){
245    let el ={}
246    el.tagName = await e.getTagName()
247    el.text = await e.text()
248     el.name = await e.getAttribute("name")
249     el.id = await e.getAttribute("id")
250     el.href = await e.getAttribute("href")
251     el.string = await e.toString()
252     el.json = await e.toJSON()
253     el.placeholder = await e.getAttribute("placeholder")
254    // let attrs = await driver.safeExecuteAsync("return arguments[0].attributes", e)
255
256    //console.log(s)
257    console.log(el)
258//     try {
259//       await el.sendKeys(indice)
260// console.log(indice, " ok")
261//     }
262//     catch(e){
263//       console.log(indice," not")
264//     }
265//
266//     indice ++
267    // if (el.text == "Nouvel Onglet"){
268    //   console.log("NOUVEAU")
269    //   await el.click()
270    // }
271  //    if(el.text == "Entrez votre terme de recherche"){
272  //      await el.type("hello world!")
273  // // await element.type(Key.Enter)
274  // console.log("saisie ok")
275  //      await driver.sleep(1000)
276  //    }
277  }
278     console.log(elements.length , " elements")
279}
280async function saisie(driver){
281console.log("saisie")
282// LeftClick on Pane "" at (451,104)
283console.log("LeftClick on Pane \"\" at (451,104)");
284let  xpath_LeftClickPane_451_104 = "/Pane[@ClassName=\"#32769\"][@Name=\"Bureau 1\"]/Window[@ClassName=\"Chrome_WidgetWin_1\"][@Name=\"Nouvel onglet - Profil 1 – Microsoft​ Edge\"]/Pane[@ClassName=\"BrowserRootView\"][@Name=\"Nouvel onglet - Microsoft Edge\"]/Pane[@ClassName=\"NonClientView\"][@Name=\"Microsoft Edge\"]/Pane[@ClassName=\"GlassBrowserFrameView\"]/Pane[@ClassName=\"BrowserView\"]/Pane[@ClassName=\"View\"]/Pane[@ClassName=\"View\"]/Pane[@ClassName=\"View\"]";
285var winElem_LeftClickPane_451_104 = await driver.element("xpath", xpath_LeftClickPane_451_104);
286if (winElem_LeftClickPane_451_104 != null)
287{
288  console.log("click")
289  await  winElem_LeftClickPane_451_104.click();
290}
291else
292{
293    console.log("Failed to find element using xpath: {xpath_LeftClickPane_451_104}");
294    //return;
295}
296
297
298// KeyboardInput VirtualKeys=""test"Keys.Return + Keys.Return" CapsLock=False NumLock=True ScrollLock=False
299console.log("KeyboardInput VirtualKeys=\"\"test\"Keys.Return + Keys.Return\" CapsLock=False NumLock=True ScrollLock=False");
300await driver.sleep(100)
301await winElem_LeftClickPane_451_104.type("test");
302await winElem_LeftClickPane_451_104.type(Keys.Return + Keys.Return);
303
304
305// LeftClick on Button "WinAppDriverUIRecorder.exe - 1 fenêtre en cours d’exécution" at (21,21)
306console.log("LeftClick on Button \"WinAppDriverUIRecorder.exe - 1 fenêtre en cours d’exécution\" at (21,21)");
307let  xpath_LeftClickButtonWinAppDriv_21_21 = "/Pane[@ClassName=\"#32769\"][@Name=\"Bureau 1\"]/Pane[@ClassName=\"Shell_TrayWnd\"][@Name=\"Barre des tâches\"]/ToolBar[@ClassName=\"MSTaskListWClass\"][@Name=\"Applications en cours d’exécution\"]/Button[@Name=\"WinAppDriverUIRecorder.exe - 1 fenêtre en cours d’exécution\"][starts-with(@AutomationId,\"C:\\Users\\psn\\dev\\WinAppDriverUIRecorder\\WinAppDriverUiRecorder.e\")]";
308var winElem_LeftClickButtonWinAppDriv_21_21 = await driver.element("xpath", xpath_LeftClickButtonWinAppDriv_21_21);
309if (winElem_LeftClickButtonWinAppDriv_21_21 != null)
310{
311  console.log("click")
312    winElem_LeftClickButtonWinAppDriv_21_21.Click();
313}
314else
315{
316    console.log("Failed to find element using xpath: {xpath_LeftClickButtonWinAppDriv_21_21}");
317    // return;
318}
319
320
321await driver.sleep(100)
322
323  console.log("fin saisie")
324}
325
Full Screen

Appium JS commands.js

Source: Appium JS commands.js Github

copy
1//Status
2//Retrieve the server’s current status
3
4// webdriver.io example
5driver.status();
6
7// wd example
8await driver.status();
9
10//Execute Mobile Command
11//Execute a native mobile command
12
13// webdriver.io example
14var result = browser.execute('mobile: scroll', {direction: 'down'})
15
16// wd example
17await driver.execute('mobile: scroll', {direction: 'down'});
18
19//Session
20//Create New Session
21//Create a new session
22
23// webdriver.io example
24let options = { desiredCapabilities: {
25    platformName: 'Android',
26    platformVersion: '7.0',
27    automationName: 'UiAutomator2',
28    app: path.resolve('path', 'to', 'app.apk')
29  }};
30  let client = driver.newSession(options);
31  
32  // wd example
33  let driver = await wd.promiseChainRemote({
34    host: '127.0.0.1',
35    port: 4723
36  });
37  let desiredCaps = {
38    platformName: 'Android',
39    platformVersion: '7.0',
40    deviceName: 'Android Emulator',
41    app: path.resolve('path', 'to', 'app.apk')
42  };
43  await driver.init(desiredCaps);
44  
45//End Session
46//End the running session
47
48// webdriver.io example
49driver.deleteSession();
50
51// wd example
52await driver.quit();
53
54//Retrieve the capabilities of the specified session
55
56// webdriver.io example
57let caps = driver.capabilities;
58
59// wd example
60let caps = await driver.sessionCapabilities();
61
62//Navigate backwards in the browser history, if possible (Web context only)
63// webdriver.io example
64driver.back();
65
66// wd example
67await driver.back()
68
69//Take a screenshot of the current viewport/window/page
70// webdriver.io example
71let screenshot = driver.takeScreenshot();
72
73// wd example
74let screenshot = await driver.takeScreenshot();
75
76//Get the current application hierarchy XML (app) or page source (web)
77// webdriver.io example
78let source = driver.getPageSource();
79
80// wd example
81let pageSource = await driver.source();
82
83//Configure the amount of time that a particular type of operation can execute for before they are aborted
84
85// webdriver.io example
86driver.setTimeouts(5000)
87
88// wd example
89await driver.setPageLoadTimeout(5000);
90
91//Set Implicit Wait Timeout
92//Set the amount of time the driver should wait when searching for elements
93// webdriver.io example
94driver.setImplicitTimeout(5000)
95
96// wd example
97await driver.setImplicitWaitTimeout(5000);
98
99//Set Script Timeout
100//Set the amount of time, in milliseconds, that asynchronous scripts executed by execute async are permitted to run before they are aborted (Web context only)
101// webdriver.io example
102driver.setAsyncTimeout(5000)
103
104// wd example
105await driver.setAsyncScriptTimeout(5000);
106
107//Get Orientation
108//Get the current device/browser orientation
109// webdriver.io example
110let orientation = driver.getOrientation();
111
112// wd example
113let orientation = await driver.getOrientation();
114
115//Get the current geo location
116// webdriver.io example
117let location = driver.getGeoLocation();
118
119// wd example
120let location = await driver.getGeoLocation();
121
122//Set the current geo location
123// webdriver.io example
124driver.setGeoLocation({latitude: "121.21", longitude: "11.56", altitude: "94.23"});
125
126// wd example
127await driver.setGeoLocation(121.21, 11.56, 10);
128
129//Get available log types as a list of strings
130// webdriver.io example
131driver.getLogTypes()
132
133// wd example
134const logTypes = await driver.logTypes();
135
136//Get the log for a given log type. Log buffer is reset after each request
137// webdriver.io example
138let logs = driver.getLogs('driver')
139
140// wd example
141const logs = await driver.log('driver');
142
143//Log event
144//Store a custom event
145// webdriver.io example
146driver.logEvent('appium', 'funEvent')
147
148// wd example
149// WD code here
150
151//Device
152//Start Activity
153//Start an Android activity by providing package name and activity name
154
155// webdriver.io example
156driver.startActivity("com.example", "ActivityName");
157
158// wd example
159await driver.startActivity({
160  appPackage: "com.example",
161  appActivity: "ActivityName"
162});
163
164//Get the name of the current Android activity
165// webdriver.io example
166let activity = driver.getCurrentActivity();
167
168// wd example
169let activity = await driver.getCurrentActivity();
170
171//Get Current Package
172//Get the name of the current Android package
173// webdriver.io example
174let package = driver.getCurrentPackage();
175
176// wd example
177let package = await driver.getCurrentPackage();
178
179//Install App
180//Install the given app onto the device
181// webdriver.io example
182driver.installApp('/Users/johndoe/path/to/app.apk')
183
184// wd example
185await driver.installAppOnDevice('/Users/johndoe/path/to/app.apk');
186// webdriver.io example
187driver.isAppInstalled('com.example.AppName')
188
189// wd example
190await driver.isAppInstalledOnDevice('com.example.AppName');
191
192// webdriver.io example
193driver.launchApp();
194
195// wd example
196await driver.launchApp();
197
198// webdriver.io example
199driver.background(10);
200
201// wd example
202await driver.backgroundApp(10);
203
204// webdriver.io example
205driver.closeApp();
206
207// wd example
208await driver.closeApp();
209
210// webdriver.io example
211driver.reset();
212
213// wd example
214await driver.resetApp();
215
216// webdriver.io example
217driver.removeApp('com.example.AppName')
218
219// wd example
220await driver.removeAppFromDevice('com.example.AppName');
221
222// webdriver.io example
223driver.activateApp(null, 'com.apple.Preferences')
224driver.activateApp('io.appium.android.apis')
225
226// wd example
227// Supports only `mobile: queryAppState` for iOS, XCUITest
228
229//Get Clipboard
230//Get the content of the system clipboard
231self.driver.get_clipboard()
232self.driver.get_clipboard_text()
233// webdriver.io example
234driver.setClipboard('happy testing', 'plaintext')
235
236// wd example
237await driver.setClipboard('happy testing', 'plaintext')
238//Emulate power state
239// webdriver.io example
240driver.powerAC('on')
241// webdriver.io example
242driver.powerCapacity(50)
243//Push File
244// webdriver.io example
245let data = new Buffer("Hello World").toString('base64');
246driver.pushFile('/data/local/tmp/file.txt', data);
247
248// wd example
249await driver.pushFileToDevice('/data/local/tmp/foo.bar', 'QXJlIHlvdXIgYmVlcnMgb2theT8=');
250//Interactions
251// webdriver.io example
252driver.shake();
253
254// wd example
255await driver.shake();
256// webdriver.io example
257driver.lock();
258
259// wd example
260await driver.lock();
261
262// webdriver.io example
263driver.lock()
264  .unlock();
265
266// wd example
267await driver.lock();
268await driver.unlock();
269
270// webdriver.io example
271driver.isLocked();
272
273// wd example
274let isLocked = await driver.isLocked();
275
276// webdriver.io example
277driver.rotateDevice(100, 100);
278
279// wd example
280driver.rotateDevice({x: 114, y: 198, duration: 5, radius: 3, rotation: 220, touchCount: 2});
281
282//Keys
283// webdriver.io example
284driver.pressKeyCode(10);
285
286// wd example
287await driver.pressKeycode(10);
288
289// webdriver.io example
290driver.longPressKeyCode(10);
291
292// wd example
293await driver.longPressKeycode(10);
294
295// webdriver.io example
296driver.hideKeyboard();
297
298// wd example
299await driver.hideDeviceKeyboard();
300// webdriver.io example
301driver.isKeyboardShown();
302
303// wd example
304await driver.isKeyboardShown();
305
306//Network
307// webdriver.io example
308driver.toggleAirplaneMode();
309
310// wd example
311await driver.toggleAirplaneMode();
312
313// webdriver.io example
314driver.toggleData();
315
316// wd example
317await driver.toggleData();
318
319// webdriver.io example
320driver.toggleWiFi();
321
322// wd example
323await driver.toggleWiFi();
324
325//PerformanceData
326// webdriver.io example
327driver.getPerformanceData('my.app.package', 'cpuinfo', 5);
328
329// wd example
330await driver.getPerformanceData('my.app.package', 'cpuinfo', 5);
331// webdriver.io example
332driver.getPerformanceDataTypes();
333
334// wd example
335await driver.getSupportedPerformanceDataTypes();
336
337//ScreenRecording
338// webdriver.io example
339driver.startRecordingScreen();
340
341//Elements
342// webdriver.io example
343$("~SomeAccessibilityId");
344// wd example
345let elementOne = await driver.elementByAccessibilityId("SomeAccessibilityID");
346let elementTwo = await driver.element("id", "SomeID");
347// webdriver.io example
348$$("~SomeAccessibilityId");
349
350// wd example
351let elementsOne = await driver.elementsByAccessibilityId("SomeAccessibilityID");
352let elementsTwo = await driver.elements("id", "SomeID");
353//click
354// webdriver.io example
355$('#SomeId').click();
356
357// wd example
358let element = await driver.elementByAccessibilityId('id', 'SomeId');
359await element.click();
360
361//SendKeys
362// webdriver.io example
363$("~SomeAccessibilityId").addValue("Enter");
364
365// wd example
366let element = await driver.elementByAccessibilityId("SomeAccessibilityID");
367await element.type("Hello world!")
368
369//Clear Elemet
370// webdriver.io example
371$("~SomeAccessibilityId").clearValue();
372
373// wd example
374let element = await driver.elementByAccessibilityId("SomeAccessibilityID");
375await element.clear();
376
377//Returns visible text for element
378// webdriver.io example
379$("~SomeAccessibilityId").getText();
380
381// wd example
382let element = await driver.elementByAccessibilityId("SomeAccessibilityID");
383await element.text();
384
385//Get an element's tag name
386// webdriver.io example
387let tagName = $("~SomeAccessibilityId").getTagName();
388
389// wd example
390let element = await driver.elementByAccessibilityId("SomeAccessibilityID");
391let tagName = await element.getTagName();
392
393//Get the value of an element's attribute
394// webdriver.io example
395let attribute = $("~SomeAccessibilityId").getAttribute("content-desc");
396
397// wd example
398let element = await driver.elementByAccessibilityId("SomeAccessibilityID");
399let tagName = await element.getAttribute("content-desc");
400
401//Determine if a form or form-like element (checkbox, select, etc...) is selected
402// webdriver.io example
403let isSelected = $("~SomeAccessibilityId").isSelected();
404
405// wd example
406let element = await driver.elementByAccessibilityId("SomeAccessibilityID");
407let isSelected = await element.isSelected();
408
409//Determine if an element is currently enabled
410// webdriver.io example
411let isEnabled = $("~SomeAccessibilityId").isEnabled();
412
413// wd example
414let element = await driver.elementByAccessibilityId("SomeAccessibilityID");
415let isEnabled = await element.isEnabled();
416
417//Determine if an element is currently displayed
418// webdriver.io example
419let isDisplayed = $("~SomeAccessibilityId").isDisplayed();
420
421// wd example
422let element = await driver.elementByAccessibilityId("SomeAccessibilityID");
423let isDisplayed = await element.isDisplayed();
424
425//Submit a FORM element
426// webdriver.io example
427let formElement = $("~SomeAccessibilityId");
428driver.elementSubmit(formElement.elementId);
429
430// wd example
431let element = await driver.elementByAccessibilityId("SomeAccessibilityID");
432await element.submit();
433
434//Gets the active element of the current session
435// webdriver.io example
436driver.getActiveElement();
437
438// wd example
439let element = await driver.active();
440
441//Test if two element IDs refer to the same element
442// webdriver.io example
443let elementOne = $("someClass");
444let elementTwo = $("someOtherClass");
445let isEqual = elementOne.isEqual(elementTwo);
446
447// wd example
448let elementOne = await driver.elementByClassName("someClass");
449let elementTwo = await driver.elementByClassName("someOtherClass");
450let isEqual = await elementOne.equalsElement(elementTwo);
451
452//Get the current context in which Appium is running
453// webdriver.io example
454let context = driver.getContext();
455
456// wd example
457let context = await driver.currentContext();
458
459//Get all the contexts available to automate
460// webdriver.io example
461let contexts = driver.getContexts();
462
463// wd example
464let contexts = await driver.contexts();
465
466//Set the context being automated
467// webdriver.io example
468let contexts = driver.getContexts();
469driver.switchContext(contexts[1]);
470// ...
471driver.switchContext('NATIVE_APP');
472
473// wd example
474let contexts = await driver.contexts();
475await driver.context(contexts[1]);
476// ...
477await driver.context('NATIVE_APP');
478
479//Mouse
480//Move the mouse by an offset of the specificed element
481// webdriver.io example
482$(element).moveTo(10, 10);
483
484// wd example
485await driver.moveTo(element, 10, 10);
486
487//Click any mouse button at the current mouse coordinates
488// webdriver.io example
489$("~SomeId").click();
490
491// wd example
492await driver.moveTo(element);
493await driver.click();
494
495//Double-clicks at the current mouse coordinates (set by moveto).
496// webdriver.io example
497$("~SomeId").doubleClick();
498
499// wd example
500await driver.moveTo(element);
501await driver.doubleclick();
502
503//Click and hold the left mouse button at the current mouse coordinates
504// webdriver.io example
505driver.moveTo(element);
506driver.buttonDown();
507
508// wd example
509await driver.moveTo(element);
510await driver.buttonDown();
511
512//Releases the mouse button previously held
513// webdriver.io example
514driver.moveTo(element);
515driver.buttonDown();
516driver.moveTo(element, 10, 10);
517driver.buttonUp();
518
519// wd example
520await driver.moveTo(element);
521await driver.buttonDown();
522await driver.moveTo(element, 10, 10);
523await driver.buttonUp();
524
525//Perform a chain or multiple chains of keyboard and pointer (touch, mouse, stylus) actions
526
527// webdriver.io example
528// Example: expressing a 1-second pinch-and-zoom
529// with a 500ms wait after the fingers first touch:
530driver.performActions([{
531    "type": "pointer",
532    "id": "finger1",
533    "parameters": {"pointerType": "touch"},
534    "actions": [
535        {"type": "pointerMove", "duration": 0, "x": 100, "y": 100},
536        {"type": "pointerDown", "button": 0},
537        {"type": "pause", "duration": 500},
538        {"type": "pointerMove", "duration": 1000, "origin": "pointer", "x": -50, "y": 0},
539        {"type": "pointerUp", "button": 0}
540    ]
541}, {
542    "type": "pointer",
543    "id": "finger2",
544    "parameters": {"pointerType": "touch"},
545    "actions": [
546        {"type": "pointerMove", "duration": 0, "x": 100, "y": 100},
547        {"type": "pointerDown", "button": 0},
548        {"type": "pause", "duration": 500},
549        {"type": "pointerMove", "duration": 1000, "origin": "pointer", "x": 50, "y": 0},
550        {"type": "pointerUp", "button": 0}
551    ]
552}]);
553
554// release an action
555driver.releaseActions();
556
557// wd example
558// Performs a 'pinch-and-zoom'
559var actions = new wd.W3CActions(driver);
560var touchInput = actions.addTouchInput();
561touchInput.pointerMove({duration: 0, x: 100, y: 100});
562touchInput.pointerDown({button: 0});
563touchInput.pause({duration: 500});
564touchInput.pointerMove({duration: 1000, origin: 'pointer', x: -50, y: 100});
565touchInput.pointerUp({button: 0});
566var secondTouchInput = actions.addTouchInput();
567secondTouchInput.pointerMove({duration: 0, x: 200, y: 200});
568secondTouchInput.pointerDown({button: 0});
569secondTouchInput.pause({duration: 300});
570secondTouchInput.pointerMove({duration: 1000, origin: 'pointer', x: 50, y: 100});
571secondTouchInput.pointerUp({button: 0});
572await actions.perform();
573
574//W3C Actions
575// Releases any previously run actions (e.g.: if a key is 'down' because of /actions, releases it using key up)
576await driver.releaseW3CActions();
577
578//Touch
579//Single tap on the touch enabled device
580// webdriver.io example
581browser.touchAction({
582    action: 'tap',
583    x: 30,
584    y: 20
585  })
586  
587  // wd example
588  // Using tapElement method
589  await driver.tapElement(elementOne);
590  
591  // Using touch actions
592  let action = new wd.TouchAction();
593  action.tap({el: element});
594  await action.perform();
595  
596//Double tap on the touch screen using finger motion events  
597// webdriver.io example
598driver.touchDoubleClick(element.elementId);
599// wd example
600// Using tapElement method
601await driver.tapElement(elementOne);
602
603// Using touch actions
604let action = new wd.TouchAction();
605action.tap({el: element});
606await action.perform();
607
608//Finger move on the screen
609// webdriver.io example
610driver.multiTouchPerform([
611    { action: 'press', options: { x: 100, y: 250 }},
612    { action: 'moveTo', options: { x: 300, y: 100 }},
613    { action: 'release' }
614  ]);
615  
616  // wd example
617  let action = new wd.TouchAction(driver);
618  action.press({x: 10, y: 10})
619        .wait(1000)
620        .moveTo({x: 50, y: 50})
621        .release();
622  await action.perform();
623  
624//Finger down on the screen  
625// webdriver.io example
626driver.touchDown(10, 10);
627
628// wd example
629// Using tapElement method
630await driver.tapElement(elementOne);
631
632// Using touch actions
633let action = new wd.TouchAction();
634action.press({x: 10, y: 10});
635action.moveTo({x: 50, y: 50});
636await action.perform();
637
638//Finger up on the screen
639// webdriver.io example
640driver.touchUp(10, 10);
641
642// wd example
643// Using tapElement method
644await driver.tapElement(elementOne);
645
646// Using touch actions
647let action = new wd.TouchAction();
648action.press({x: 10, y: 10});
649action.release({x: 20, y: 20});
650await action.perform();
651
652//Long press on the touch screen using finger motion events
653// webdriver.io example
654driver.touchPerform({
655    action: 'longPress',
656    options: {
657      element: element
658    }
659  });
660  
661  // wd example
662  // Using touch actions
663  let action = new wd.TouchAction();
664  action.longPress({el: element});
665  await action.perform();
666  
667//Web
668//SetWindow  
669// webdriver.io example
670driver.switchToWindow("handle");
671
672// wd example
673await driver.window("handle");
674
675//Close the current window (Web context only)
676// webdriver.io example
677driver.closeWindow();
678
679// wd example
680await driver.close();
681
682//Retrieve the current window handle (Web context only)
683// webdriver.io example
684let handle = driver.getWindowHandle();
685
686// wd example
687let windowHandle = await driver.windowHandle();
688
689//Retrieve the list of all window handles available to the session (Web context only)
690// webdriver.io example
691let handles = driver.getWindowHandles();
692
693// wd example
694let windowHandle = await driver.windowHandles();
695
696//Get the current page title (Web context only)
697// webdriver.io example
698let handle = driver.getTitle();
699
700// wd example
701let title = await driver.title();
702
703//Get the size of the specified window (Web context only)
704// webdriver.io example
705let position = driver.getWindowRect();
706
707// wd example
708let handleOneSize = await driver.getWindowSize();
709let handleTwoSize = await driver.getWindowSize("handleName");
710
711//Navigation
712//Navigate to a new URL (Web context) or open an Appium deep link (Native)
713// webdriver.io example
714driver.url("http://appium.io");
715
716// wd example
717await driver.get("http://appium.io/");
718
719//Retrieve the URL of the current page (Web context only)
720// webdriver.io example
721let url = driver.getUrl();
722
723// wd example
724let url = await driver.url();
725
726//Navigate backwards in the browser history, if possible (Web context only)
727// webdriver.io example
728driver.back();
729
730// wd example
731await driver.back();
732
733//Navigate forwards in the browser history, if possible (Web context only)
734// webdriver.io example
735driver.forward();
736
737// wd example
738await driver.forward();
739
740//Refresh the current page. (Web context only)
741// webdriver.io example
742driver.refresh();
743
744// wd example
745await driver.refresh();
746
747//Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame (Web context). Run a native mobile command (Native Context).
748// webdriver.io example
749var result = browser.execute(function(a, b, c, d) {
750    // browser context - you may not access client or console
751    return a + b + c + d;
752  }, 1, 2, 3, 4)
753  
754  // node.js context - client and console are available
755  console.log(result); // outputs: 10
756  
757  // wd example
758  await driver.execute('document.title');
759  
760//Execute Async Script
761//Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame (Web context only)  
762// webdriver.io example
763driver.setAsyncTimeout(5000)
764var result = browser.executeAsync(function(a, b, c, d, done) {
765    // browser context - you may access neither client nor console
766    setTimeout(function() {
767        done(a + b + c + d);
768    }, 3000);
769}, 1, 2, 3, 4)
770
771// node.js context - client and console are available
772console.log(result); // outputs: 10
773
774// wd example
775await driver.safeExecuteAsync('document.title');
776
777//Change focus to another frame on the page (Web context only)
778// webdriver.io example
779driver.switchToFrame(3);
780
781// wd example
782await driver.frame(3);
783
784//Retrieve all cookies visible to the current page (Web context only)
785// webdriver.io example
786let cookies = driver.getCookies();
787
788// wd example
789let cookies = await driver.allCookies();
790
791//Set a cookie (Web context only)
792// webdriver.io example
793driver.setCookies([{
794    name: 'myCookie',
795    value: 'some content'
796  }]);
797  
798  // wd example
799  let cookies = await driver.setCookie({name: 'foo', value: 'bar'});
800  
801//Delete the cookie with the given name (Web context only)
802// webdriver.io example
803driver.deleteCookies("cookie_name");
804
805// wd example
806await driver.deleteCookie("cookie_name");
807
808//Delete all cookies visible to current page (Web context only)
809// webdriver.io example
810driver.deleteCookies();
811
812// wd example
813await driver.deleteAllCookies();
814
815
816
817
818
Full Screen

mobiletest.js

Source: mobiletest.js Github

copy
1		
2		var moment=require('moment')
3		var fs = require('fs');
4		var wd = require('wd')
5		var http = require("http");
6		var io = require('socket.io-client') //creating a client socket to connect to aqua server
7        var Controller = require('appium-controller')
8        var mysql = require('mssql')
9        //var Jimp = require('jimp');// for image crop
10        //var BlinkDiff=require('blink-diff')//for image comparision
11
12        /*  var server = http.createServer(function(request, response) {
13		 console.log(request);
14		 console.log(response)
15		 }); */
16
17				//var iop = require('socket.io')(server); 
18				
19		var args = process;
20		var splitcmd = args.title.split(' ')
21	
22		console.log(splitcmd,'starting...............')
23		var jsonname=splitcmd[splitcmd.length - 1]
24			console.log(jsonname)
25		var sockno = splitcmd[splitcmd.length - 2]
26			console.log(sockno)
27
28			//  var socket = io.connect('http://localhost:'+port);
29			 
30			 /******************ZMQ******************/
31
32	var zmq = require('zmq')
33//console.log(zmq, "zmq")
34	var dealer = zmq.socket('dealer');
35//	console.log(dealer, "dwealer print")
36	//dealer.identity = 'Bot1'
37	dealer.data = 'datainside'
38
39
40
41
42console.log("automation on port-" + sockno)
43dealer.connect('tcp://localhost:' + sockno);
44
45
46// Register to monitoring events
47dealer.on('connect', function(fd, ep) {
48    console.log('connect, endpoint:', ep);
49});
50dealer.on('connect_delay', function(fd, ep) {
51    console.log('connect_delay, endpoint:', ep);
52});
53dealer.on('connect_retry', function(fd, ep) {
54    console.log('connect_retry, endpoint:', ep);
55});
56dealer.on('listen', function(fd, ep) {
57    console.log('listen, endpoint:', ep);
58});
59dealer.on('bind_error', function(fd, ep) {
60    console.log('bind_error, endpoint:', ep);
61});
62dealer.on('accept', function(fd, ep) {
63    console.log('accept, endpoint:', ep);
64});
65dealer.on('accept_error', function(fd, ep) {
66    console.log('accept_error, endpoint:', ep);
67});
68dealer.on('close', function(fd, ep) {
69    console.log('close, endpoint:', ep);
70});
71dealer.on('close_error', function(fd, ep) {
72    console.log('close_error, endpoint:', ep);
73});
74dealer.on('disconnect', function(fd, ep) {
75    console.log('disconnect, endpoint:', ep);
76});
77
78// Handle monitor error
79dealer.on('monitor_error', function(err) {
80    console.log('Error in monitoring: %s, will restart monitoring in 5 seconds', err);
81    setTimeout(function() {
82        dealer.monitor(500, 0);
83    }, 5000);
84});
85
86// Call monitor, check for events every 500ms and get all available events.
87console.log('Start monitoring...');
88dealer.monitor(500, 0);
89
90dealer.on('message', function(msg) {
91
92
93})
94
95
96
97
98
99/**********end********************/
100
101
102			
103      //var us = require('underscore')
104		var stepno, stepdescription, expected, Hop, screenname, imgname, fieldname, type, keyword, selectorval;
105		var testdata, brdreference, application, automatable, errdetails, status, exedatetime;
106		var mainid='android.support.v4.widget.DrawerLayout'
107
108		global.status = "";
109	    global.msg = "";
110        global.eventStatus="";
111		var currentpath = __dirname;
112		var datajsonpath = currentpath + '/'+ jsonname +'.json'
113		//var datajsonpath = currentpath + '/preseller1.json'
114		var rawdatafromfile = fs.readFileSync(datajsonpath,"utf8");
115		rawdatafromfile.toString()
116		rawdatafromfile = rawdatafromfile.trim()
117		var scriptdetails = JSON.parse(rawdatafromfile);
118		var stepdata = scriptdetails.scriptstep;
119		var argodata=scriptdetails.argodata
120		var socket_no=argodata.driver.port
121		console.log( argodata)
122		var appconfig=argodata.desiredCapabilities.app.split('/')
123		console.log(appconfig)
124		var crypto = require('crypto');
125		var d;
126		var date = new Date().toString();
127		date = date.replace(/ /g, "-")
128		date = date.replace(/:/g, "-")
129		console.log(date)
130		//console.log(stepdata)
131    //  appiumController.startAppium( )
132		//console.log(argodata)
133
134		/*browserName:'chrome', 
135		androidPackage:"com.android.chrome",
136		browserConnectionEnabled:true,
137		mobileEmulationEnabled:true,
138		chromeOptions: {
139        'androidPackage': 'com.android.chrome',
140       }*/
141		var  desiredCapabilities = {
142		platformName: argodata.desiredCapabilities.platformName,
143		platformVersion: argodata.desiredCapabilities.platformVersion,
144		deviceName:  argodata.desiredCapabilities.deviceName,
145		automationName: argodata.desiredCapabilities.automationName,		
146		autoGrantPermissions:argodata.desiredCapabilities.autoGrantPermissions,
147		appPackage:appconfig[0],
148		uid: argodata.desiredCapabilities.uid,
149		appActivity:appconfig[1],
150		// appWaitActivity:'com.ivy.cpg.view.login.LoginScreen,com.ivy.sd.png.view.ScreenActivationActivity,com.ivy.sd.png.view.DummyLaunchActivity,com.ivy.sd.png.view.InitiativeActivity',
151		//	  appActivity: 'com.ivy.sd.png.view.ScreenActivationActivity',
152		// app: currentpath + "/ivycpg_v128_1515.apk",
153		//useNewWDA: argodata.desiredCapabilities.useNewWDA,
154		noReset: argodata.desiredCapabilities.noReset
155		//appPackage:"com.msf.currenex.mobile",
156		//appActivity:"com.msf.currenex.mobile.login.LoginActivity"
157		}
158        var driver = wd.promiseChainRemote({
159          host: argodata.driver.host,
160          port: argodata.driver.port          
161        })
162
163/*socket_call(socket_no);
164
165function socket_call(socket_no) {
166    var serv_status =  server.listen(socket_no)
167    console.log("trying to establish conn on port--"+socket_no) 
168  if (serv_status.listening) {
169  console.log("socket_no running on "+socket_no)
170}}
171
172
173iop.on('connection', function(socketp) {
174console.log(socketp)
175
176socketp.on('mob-exeres', function(data) {
177console.log(data)
178
179        tempobj.scriptstep = []
180        scriptdetails.scriptstep[global.cflag].executiondate = errexedatetime
181        scriptdetails.scriptstep[global.cflag].status = "broke";
182        scriptdetails.scriptstep[global.cflag].actual = "script failure";
183        tempobj.currobj = scriptdetails.scriptstep[global.cflag]
184        socket.emit('auto-exeres', tempobj)
185
186});
187
188});*/
189       // console.log(eval("select * from Appdata_GRN_Detail where GD_GH_Id='"+Currentdate()+"'"))
190          // console.log(driver,"68")
191		function getImageData(val) {
192			var readStream = fs.createReadStream(val);
193			var hash = crypto.createHash('sha1')
194			global.array = [];
195			readStream.on('data', function(chunk) {
196				//hash.update(chunk)
197				global.array.push(chunk)
198			  })
199			  .on('end', function(chunk) {
200				global.dateobj;
201				global.dateobj = Buffer.concat(global.array).toString('base64')
202				//global.dateobj.newdate=new Date();
203				//console.log(global.dateobj)
204
205				console.log(hash.digest('hex'), "41");
206			  })
207			  return global.dateobj
208		}
209		function delay() {
210    // `delay` returns a promise
211        return new Promise(function(resolve, reject) {
212        console.log("inside  delay functions promise");
213        console.log("the global eventStatus is: "+global.eventStatus)
214        let e = global.eventStatus;
215        global.eventStatus = "";
216        if (e == "success") {
217            resolve(e);
218        }
219        if (e == "fail") {
220            console.log("Enter Fail Text")
221            resolve(e);
222        }
223        console.log("End of Delay function");
224    });
225    }
226        function sendtramdata(stepval,ind,status,errdetails,exedatetime,image ){
227		//function sendtramdata(status, errdetails, exedatetime, stepdata, imgname) {
228			console.log("sending data to tram......")
229			//getImageData(foldername + "/" + imgname)
230			// console.log(global.dateobj)
231			/*
232			  console.log(global.dateobj)*/
233			var tempobj = {
234			  "tindetails": scriptdetails.tindetails,
235			  "username": scriptdetails.username,
236			  "insindex": scriptdetails.insindex,
237			  "argodata": scriptdetails.argodata,
238			
239			}
240			//var tempobj={}
241			tempobj.scriptstep = []
242			stepval.browser = "chrome";
243			stepval.executiondate = exedatetime
244			stepval.screenshot =image
245			stepval.status = status;
246			stepval.actual = errdetails;
247			tempobj.scriptstep.push(stepval)
248			tempobj.currobj = stepval
249			//console.log(tempobj,"80")
250		//	console.log("stepval.screenshot", stepval.screenshot , " endiiinggggggggggggggggggggg")
251			if(ind==stepdata.length-1)
252			{
253				console.log("Appium Stop")
254				var auto_json = JSON.stringify(tempobj)
255				dealer.send(auto_json);
256				dealer.close();
257
258			//	socket.emit('auto-exeres', tempobj)
259				Controller.stopAppium({port:argodata.driver.port});
260
261			} else {
262				console.log("Result has been emitted to agent")
263			//	socket.emit('auto-exeres', tempobj)
264			var auto_json = JSON.stringify(tempobj)
265				dealer.send(auto_json);
266			//	dealer.close();
267			}
268		 	
269			//console.log(tempobj,"-------------------------")
270		}
271
272
273		//==============================================================================
274//function block
275//------------------------------------------------------------------------------
276//Function for ensuring that the test cafe script continues and does not end abruptly
277function delay() {
278    // `delay` returns a promise
279    return new Promise(function(resolve, reject) {
280        console.log("inside  delay functions promise");
281        console.log("the global eventstatus is: "+global.eventStatus)
282        let e = global.eventStatus;
283        global.eventStatus = "";
284        if (e == "success") {
285            resolve(e);
286        }
287        if (e == "fail") {
288            console.log("Enter Fail Text")
289            resolve(e);
290        }
291        console.log("End of Delay function");
292    });
293}
294
295function scrollToView(start,direction,distance){
296	// Start is the starting point - object with properties x and y - absolute position
297	// direction is string with values up or down for vertical scroll; left or right for horizontal scroll
298	// distance is object with properties x and y - must give the distance to be moved in x axis and in y axis
299	// target location will be calculated by subtracting distance from start point if upward movement and by addition if downward movement
300
301	console.log("start",start, "direction",direction, "distance", distance)
302	if (direction == "up"){
303		var target = parseInt(start.y) - parseInt(distance.y)
304		var action = new wd.TouchAction(driver);
305		action.press(start);
306		action.wait(2000)
307		action.moveTo({x: start.x, y: target});
308		action.release().perform();
309
310
311	}
312
313	else if (direction == "down"){
314
315		var target = parseInt(start.y) + parseInt(distance.y)
316		var action = new wd.TouchAction(driver);
317		action.press(start);
318		action.wait(2000)
319		action.moveTo({x: start.x, y: target});
320		action.release().perform();
321		
322
323	}
324	else if (direction == "left"){
325
326		var target = parseInt(start.x) - parseInt(distance.x)
327		var action = new wd.TouchAction(driver);
328		action.press(start);
329		action.wait(2000)
330		action.moveTo({x: target, y: start.y});
331		action.release().perform();
332
333	}
334
335	else if (direction == "right"){
336
337		var target = parseInt(start.x) + parseInt(distance.x)
338		var action = new wd.TouchAction(driver);
339		action.press(start);
340		action.wait(2000)
341		action.moveTo({x: target, y: start.y});
342		action.release().perform();
343
344	}
345
346}
347
348
349async function scrollToFindCombolist(selector_type,selector_val,testdata,direc,mode){
350	var temp1;var temp2="";var flag=false;
351						 	do{
352						 		temp1=temp2;
353						 		console.log(temp1,temp2,selector_val)						 		
354						 		var finddata=await driver.elementOrNull('xpath',selector_val+"[@text='" + testdata + "']")
355						 		if(finddata==null)
356						 		{
357						 			    await driver.setImplicitWaitTimeout(8000)
358						 			    var selector2=await driver.elements(selector_type,selector_val)			
359						 		        var gettext=await selector2[selector2.length-1].text()
360						 		        console.log(selector2.length,gettext)
361                                        temp2=gettext;
362						 		    	var start=await selector2[selector2.length-1].getLocation()
363						 		    	var direction=direc
364						 		    	var distance=await selector2[0].getLocation()
365						 		    	if(direction=='up'){
366						 		    	distance.x=start.x-distance.x
367						 		    	distance.y=start.y-distance.y+10
368						 		    	console.log(distance,start)
369						 		    	scrollToView(start,direction,distance)
370
371						 		    	}else if(direction=='down'){
372                                        console.log(start,distance)
373						 		    	start.x=start.x-distance.x
374						 		    	start.y=start.y-distance.y
375						 		    	console.log(start,distance)
376						 		    	scrollToView(distance,direction,start)	
377						 		    	}
378						 		    											
379						 		}else {console.log("found")						 		      
380						 			if(mode=='click'){
381						 		    	flag=true;
382						 		    	await driver.clickElement(finddata)						 		    		
383						 		    	}else if(mode=='verify'){
384						 		    	 flag=true;
385						 		    	 global.status = "Pass";global.eventStatus="success"
386								         global.msg = "The button '" + fieldname + "' on the page '" + screenname + "' was successfully clicked";
387									}
388									break;
389						 		}
390						 		
391						 	}while(temp1!=temp2)
392
393						 	return flag;					 	
394
395}
396async function scrollToFindElement(selector_type,selector_val,testdata,direc,mode)
397{
398	console.log("scrollToFindElement function")
399	var temp1;var temp2="";var flag=false;
400	var finddata;var s_type;var s_val;
401	        if(selector_type=='id'){
402	             s_type='xpath' 
403	             s_val="//android.widget.TextView[@text='"+testdata+"']"
404	         }else {
405	         	s_type=selector_type;
406	         	s_val=selector_val
407	         }
408						 		              
409						 	do{
410						 		temp1=temp2;
411						 		console.log(temp1,temp2,selector_val)		
412						 		finddata=	await driver.elementOrNull(s_type,s_val)		 		
413						 		
414						 		if(finddata==null)
415						 		{
416						 			    await driver.setImplicitWaitTimeout(4000)
417						 			    var selector2;
418
419						 			    selector_type=='xpath' ? selector2=await driver.elements('xpath', "//android.widget.TextView")
420						 		                       : selector2=await driver.elements(selector_type,"[@class=android.widget.EditText]");
421						 		                   //await driver.elements(selector_type,selector_val)	
422
423						 		        /*for(var j=0;j<selector2;j++){
424						 		          	console.log(await selector2[j].text())
425						 		         }   */ 
426						 		         console.log()     		
427						 		        var gettext=await selector2[selector2.length-1].text()
428						 		        console.log(selector2.length,gettext)
429                                        temp2=gettext;
430						 		    	var start=await selector2[selector2.length-1].getLocation()
431						 		    	var direction=direc
432						 		    	var distance=await selector2[0].getLocation()
433						 		    	console.log(start,distance)
434						 		    	if(direction=='up'){
435						 		    	distance.x=start.x-distance.x
436						 		    	distance.y=start.y-distance.y
437						 		    	console.log(start,distance)
438						 		    	scrollToView(start,direction,distance)
439
440						 		    	}else if(direction=='down'){
441						 		    	console.log(start,distance)
442						 		    	start.x=start.x-distance.x
443						 		    	start.y=(start.y-distance.y)-10
444						 		    	console.log(start,distance)
445						 		    	scrollToView(distance,direction,start)						 		    		
446                                        
447						 		    	}
448						 		    											
449						 		}else {console.log("found")						 		      
450						 			if(mode=='click'){
451						 		    	flag=true;
452						 		    	await driver.clickElement(finddata)						 		    		
453						 		    	}else if(mode=='verify'){
454						 		    	 flag=true;
455						 		    	 
456									}
457									break;
458						 		}
459						 		
460						 	}while(temp1!=temp2)
461
462						 	return flag;					 	
463}
464
465
466async function scrollTotextboxElement(selector_type,selector_val,testdata,direc,mode)
467{
468	console.log("scrollTotextboxElement function")
469	console.log(selector_type,selector_val, direc, mode )
470	var temp1;var temp2="";var flag=false;
471	var finddata;var s_type;var s_val;
472	       
473						 		              
474						 	do{
475						 		temp1=temp2;
476						 		console.log(temp1,temp2,selector_val)		
477						 		finddata=	await driver.elementOrNull(selector_type,selector_val)		 		
478						 		
479						 		if(finddata==null)
480						 		{
481						 			    await driver.setImplicitWaitTimeout(4000)
482						 			    var selector2;
483
484						 			    selector2=await driver.elements('xpath', "//android.widget.Button")
485						 		                     
486						 		                   //await driver.elements(selector_type,selector_val)	
487
488						 		        /*for(var j=0;j<selector2;j++){
489						 		          	console.log(await selector2[j].text())
490						 		         }   */ 
491						 		         console.log("INside if condn", selector2 )     		
492						 		        var gettext=await selector2[selector2.length-1].text()
493						 		        console.log(selector2.length,gettext)
494                                        temp2=gettext;
495						 		    	var start=await selector2[selector2.length-1].getLocation()
496						 		    	var direction=direc
497						 		    	var distance=await selector2[0].getLocation()
498						 		    	console.log(start,distance)
499						 		    	if(direction=='up'){
500						 		    	distance.x=start.x-distance.x
501						 		    	distance.y=start.y-distance.y
502						 		    	console.log(start,distance)
503						 		    	scrollToView(start,direction,distance)
504
505						 		    	}else if(direction=='down'){
506						 		    	console.log(start,distance)
507						 		    	start.x=start.x-distance.x
508						 		    	start.y=(start.y-distance.y)-10
509						 		    	console.log(start,distance)
510						 		    	scrollToView(distance,direction,start)						 		    		
511                                        
512						 		    	}
513						 		    											
514						 		}else {console.log("found")						 		      
515						 			if(mode=='click'){
516						 		    	flag=true;
517						 		    	await driver.clickElement(finddata)						 		    		
518						 		    	}else if(mode=='verify'){
519											 console.log("Mode as Verify")
520											 e1 = await driver.elementOrNull(selector_type,selector_val)
521										
522						 		    	 flag=true;
523						 		    	 
524									}
525									break;
526						 		}
527						 		
528						 	}while(temp1!=temp2)
529
530						 	return flag;					 	
531}
532
533
534async function tester(){
535          console.log(stepdata.length,"ENterrrrr")
536		  for (var i=0;i<stepdata.length;i++){
537		  	 //var path1 = "C:cd/appium/screens/log" + i.toString()
538		     //console.log(path1)
539                console.log(stepdata[i].hasOwnProperty('xpath'),stepdata[i].hasOwnProperty('css'),"363")
540							
541			// if(stepdata[i].xpath.toLowerCase() != 'x')
542			if ((stepdata[i].hasOwnProperty('xpath'))&&(stepdata[i].xpath != 'x')) 
543				{
544					console.log("xpath")
545					await test(stepdata[i],i,"xpath",stepdata[i].xpath).then(console.log(i,stepdata[i]))
546					if(i < stepdata.length-1 )
547					{
548					var ss1;
549						//if( (type=='image-capture' && stepdata[i].keyword=='verify'))
550						//{
551                         // var img_name= stepdata[i].testdata.split(',')
552                         //  ss1=await getImageData('mobile_pic' + "/" +img_name[2]+".png")
553                          // console.log("image-captured")
554					//	}
555					//	else  if(stepdata[i].screenname!=stepdata[i+1].screenname ||stepdata[i].keyword=='verify')
556						// {
557							  ss1=await driver.takeScreenshot();console.log("Screenshotttttttttt")				              
558				        // }
559					} else
560					{
561						var ss1=await driver.takeScreenshot();console.log("Screenshotttttttttt")
562		                
563					}
564						console.log(global.status + "   " + global.msg);
565						status = global.status;  errdetails = global.msg;  exedatetime = new Date();
566
567
568				}//else if(stepdata[i].css.toLowerCase() != 'x')
569				else if ((stepdata[i].hasOwnProperty('css'))&&(stepdata[i].css != 'x'))
570						{ 
571							console.log("selector")
572							await test(stepdata[i],i,"id",stepdata[i].css).then(console.log(i,stepdata[i]))
573							if(i < stepdata.length-1 ){
574					    var ss1;
575					   // if( (stepdata[i].type=='image-capture' && stepdata[i].keyword=='verify')){
576                         // var img_name= stepdata[i].testdata.split(',')
577
578                          // ss1=await getImageData('mobile_pic' + "/" +img_name[2]+".png")
579                         //  console.log(ss1,"image-capture")
580					 //   }else  if(stepdata[i].screenname!=stepdata[i+1].screenname || stepdata[i].keyword=='verify') {
581							  ss1=await driver.takeScreenshot();console.log("Screenshotttttttttt")				              
582				           //    }
583				        } else{
584						var ss1=await driver.takeScreenshot();console.log("Screenshotttttttttt")
585		                
586						}
587						console.log(global.status + "   " + global.msg);
588						status = global.status;  errdetails = global.msg;  exedatetime = new Date();
589
590		                    
591						}
592
593		     await sendtramdata(stepdata[i],i,status,errdetails,exedatetime,ss1)
594			}
595		  //driver.safeExecuteAsync(function(){
596			return "Tests have been run"
597		}
598
599 driver.init(desiredCapabilities)
600      .then(function(){
601		
602        console.log("Before Starting Mobile Automation");
603        var exemesg = {status:"testcafe started"}
604        //var exemesg_auto_json=JSON.stringify(exemesg)
605			//  socket.emit('auto-exeres', exemesg)
606			var exemesg_auto_json = JSON.stringify(exemesg);
607
608			dealer.send(exemesg_auto_json);
609	
610		tester()
611        })
612
613
614async function test(val,i,selector_type,selector_val){
615			console.log("Inside test function with item ",i)
616
617			global.status = "";
618			global.msg = "";
619            global.eventStatus="";
620			stepno = val.stepno;
621			stepdescription = val.stepdescription;
622			expected = val.expected;
623			// Not available in the merged JSON --- Hop = val.Hop;
624			screenname = val.screenname;
625			imgname = val.screenname + ".png"
626			fieldname = val.fieldname;
627			type = val.type.toLowerCase();
628			keyword = val.keyword.toLowerCase();
629			//selectorval = val.css;
630			testdata = val.testdata;
631		//	xpath = val.xpath
632			id = selector_val
633			selectorval = selector_val;
634
635                if (testdata.substring(0, 1) == "^") {    
636	        		console.log(testdata, "Data before convert",testdata.substring(1))            
637	                testdata = eval(testdata.substring(1))
638	                //testdata = eval(testdata.substring(testdata.indexOf("^")+1))
639	               // testdata = stepdata
640	                console.log(testdata, "Data after convert")
641		        }
642		        if (selector_val.substring(0, 1) == "^") {                
643		                console.log(selector_val, "Selector before convert")
644		                selector_val = eval(selector_val.substring(1))
645		                console.log(selector_val, "Selector after convert")
646		                selectorval = selector_val;
647		                //testdata = eval(testdata.substring(testdata.indexOf("^")+1))
648		        }
649			//console.log(id)
650			
651			// Not available in the merged JSON ---brdreference = val.brdreference;
652			// Not available in the merged JSON ---application = val.application;
653			// Not available in the merged JSON ---automatable = val.automatable;
654			//errdetails;
655			//status;
656			//exedatetime;
657
658			console.log("stepno:" + stepno + "  screenname" + screenname + "  fieldname:" + fieldname + "   type: " + type + "  keyword: " + keyword);
659			console.log("testdata: " + testdata + "   selectorval: " + selectorval);
660console.log(await driver.getCurrentActivity(),"Appium current activity")
661await driver.setImplicitWaitTimeout(10000)
662switch (keyword)
663{
664		case "input":
665				switch (type)
666				 {
667				 	case "url":
668				 	//await driver.window("handle");
669
670				 	await driver.get('http://appium.io')
671
672				 	console.log("Naviagte into url")
673
674				 	break;
675				 	case "toggle":
676				 	console.log("Eter into toggle")
677				 	driver.executeScript("mobile: shell", 'adb shell settings get global airplane_mode_on');
678				 	//driver.setConnection(Connection.AIRPLANE);
679
680
681				 	//await driver.setNetworkConnection(0)//toggleAirplaneMode();
682				 	
683
684				 	break;
685				 	
686		
687					 case "combobox":
688					 //e1 = await driver.elementOrNull(selector_type,selector_val)
689					 var find_el=await driver.elementOrNull(selector_type,selector_val)
690					 if (!find_el ){
691						 console.log("Not found sec")
692					 global.status = "Fail";global.eventStatus="fail"
693					 global.msg = "The element'" + fieldname + "' on the page '" + screenname + "' was not successfully selected from the dropdown";
694					 } else {
695						console.log("Found section from scroll")
696					 //var c_option=await e1.getAttribute('className')
697					  //await driver.click(selector_type,selector_val)
698					  await driver.setImplicitWaitTimeout(Number('5'))
699					 e1 = await driver.element(selector_type,selector_val)
700					 await driver.clickElement(e1)
701					 if(await driver.elementOrNull('xpath','//android.widget.TextView')){
702					 console.log("Enter into textview")
703					 var d1=await scrollToFindCombolist('xpath',"//android.widget.TextView",testdata,'down','click')
704
705					 if(d1){																
706					 global.status = "Pass";global.eventStatus="success"
707					 global.msg = "The '" + testdata + "' was successfully selected from the dropdown '" + fieldname + "' in the page ' " + screenname + "' ";
708					 }else{	
709					 var d2=await scrollToFindCombolist('xpath',"//android.widget.TextView",testdata,'up','click')	
710					 if(d2)	{
711					 global.status = "Pass";global.eventStatus="success"
712					 global.msg = "The '" + testdata + "' was successfully selected from the dropdown '" + fieldname + "' in the page ' " + screenname + "' ";
713
714					 } else {
715					 global.status = "Fail";global.eventStatus="fail"
716					 global.msg = "The '" + testdata + "' was not successfully selected from the dropdown '" + fieldname + "' in the page ' " + screenname + "' ";
717
718					 }	
719					 }	
720					 }else if(await driver.elementOrNull('xpath','//android.widget.CheckedTextView')){
721						 console.log("enter into checkedtextview")
722					 var d1=await scrollToFindCombolist('xpath',"//android.widget.CheckedTextView",testdata,'down','click')
723					 if(d1){									
724					 global.status = "Pass";global.eventStatus="success"
725					 global.msg = "The '" + testdata + "' was successfully selected from the dropdown '" + fieldname + "' in the page ' " + screenname + "' ";
726					 }else{	
727					 var d2=	await scrollToFindCombolist('xpath',"//android.widget.CheckedTextView",testdata,'up','click')	
728					 if(d2)	{
729					 global.status = "Pass";global.eventStatus="success"
730					 global.msg = "The '" + testdata + "' was successfully selected from the dropdown '" + fieldname + "' in the page ' " + screenname + "' ";
731
732					 } else {
733					 global.status = "Fail";global.eventStatus="fail"
734					 global.msg = "The '" + testdata + "' was not successfully selected from the dropdown '" + fieldname + "' in the page ' " + screenname + "' ";
735
736					 }	
737					 }
738					 }												                                           
739					 }
740					d=await delay()
741		 break;	
742 	
743                    case "button":
744							console.log(selectorval)
745							console.log("inside the button keyword")
746							//waitFor(wd.asserters.isDisplayed(fieldname),2000,function(err,el){
747							//	console.log(el)
748							//})
749							e1 = await driver.elementOrNull(selector_type,selector_val)
750							//await driver.setImplicitWaitTimeout(15000)
751							if (e1 === null){
752							console.log(fieldname," not found...waiting for 10 seconds")							
753							e1 = await driver.elementOrNull(selector_type,selector_val)
754							//await driver.setImplicitWaitTimeout(15000)
755							if (e1 === null){
756							//e2 = await driver.active();//console.log(e2)
757							global.status = "Fail";global.eventStatus="fail"
758							global.msg = "ERROR: Unable to click the button'" + fieldname + "' in the ' " + screenname + "' page. " ;
759							}else{
760							//console.log(await driver.getAttribute(e1,'resourceId')	)
761							console.log(e1, "e1");
762							await driver.clickElement(e1)
763							global.status = "Pass";global.eventStatus="success"
764							global.msg = "The button '" + fieldname + "' on the page '" + screenname + "' was successfully clicked";
765							}
766							}
767							else{
768								console.log(e1, "e1");
769							console.log(fieldname," found... going to click it...")
770							//console.log(await driver.getAttribute(e1,'resourceId'))
771
772							await driver.clickElement(e1)							
773							global.status = "Pass";global.eventStatus="success"
774							global.msg = "The button '" + fieldname + "' on the page '" + screenname + "' was successfully clicked";
775							}
776					d=await delay()
777					break;
778							
779					case "back-screen":
780							//console.log(selectorval)
781							console.log("inside the back keyword")
782						    e1= await driver.back();							
783							if (e1 === null){
784										global.status = "Fail";global.eventStatus="fail"
785										global.msg = "ERROR: Unable to enter the details '" + fieldname + "' in the ' " + screenname + "' page.  " ;
786									}
787									else{
788										global.status = "Pass";global.eventStatus="success"
789									    global.msg = "The element'" + fieldname + "' on the page '" + screenname + "' was successfully entered";
790									}
791								 d=await delay()
792					break;
793					
794					case "textbox":
795							//console.log(selectorval)
796							console.log("inside the textbox keyword",testdata)
797
798							e1 = await driver.elementOrNull(selector_type,selector_val)
799							console.log(e1, "textbox checking")
800								if (e1 === null){
801									console.log(fieldname," not found...waiting for 10 seconds")	
802									var d1=await scrollTotextboxElement(selector_type,selector_val,testdata,'up','verify')								
803									
804									//await driver.setImplicitWaitTimeout(10000)
805									if(d1){ 
806										await e1.clear();
807										await driver.type(e1,testdata)
808										await driver.hideDeviceKeyboard();										
809										global.status = "Pass";global.eventStatus="success"
810										global.msg = "The testdata'" + testdata + "in the field" + fieldname + "' on the page '" + screenname + "' was successfully entered";
811									} else {
812									    global.status = "Fail";global.eventStatus="fail"
813										global.msg = "ERROR: Unable to enter the details '" + testdata + "' in the field' "+ fieldname + 'in the ' + screenname + "' page." ;
814									    }	
815
816								}else{
817									console.log(fieldname," found .. going to type text into it")
818									await e1.clear();
819									await driver.type(e1,testdata)	
820									await driver.hideDeviceKeyboard();								
821									global.status = "Pass";global.eventStatus="success"
822									global.msg = "The testdata'" + testdata + "in the field" + fieldname + "' on the page '" + screenname + "' was successfully entered";
823								}
824
825							//e1 = driver.elementIfExists(selector_type,fieldname)
826
827                            d=await delay()
828					break;	
829				 	default:
830                    global.status = "Fail";
831					global.msg = "Fail:Incorrect Type '"+type+"' in Input keyword.Please check...";								
832				 	break;
833
834				  }
835		break;
836	
837		case "verify":
838				switch (type)
839				 {  
840				
841				 	case "tabletext":
842				 	          var tdata=testdata.split(/>>(.*)/);
843						       e1= await driver.elementOrNull('xpath',"//android.widget.TextView[@text='"+ tdata[0]+"']")
844						       console.log(e1)
845						       if(e1!=null)
846						       {
847                                  var flag1=false;						                
848						           var selector3 = await driver.elements("xpath","//*[@text='"+ tdata[0]+"']/following-sibling::"+selectorval)
849						           console.log(selector3.length)
850						           if(selector3.length==0){
851						                 	global.status = "Fail";global.eventStatus="fail"
852								             global.msg = "The element '" + txt + "' on the page '" + screenname + "' was successfully not verified against the expected value '" + tdata[1] + "'";
853						           }
854						           for(var ins in selector3)	{
855
856						        	  var txt;
857						        	  txt= tdata[1].substring(0,1)=='#' ? await driver.getAttribute(selector3[ins],'resourceId') : await selector3[ins].text() ;
858						        	  var datas=tdata[1].substring(0,1)=='#' ? tdata[1].substring(1) : tdata[1];
859
860						        	  if(txt==datas )	  { 	flag1=true;console.log("success: ",txt)     	  }
861						        	  if(ins==selector3.length-1)	  {
862						        	  	if(flag1){
863                                            global.status = "Pass";global.eventStatus="success"
864								            global.msg = "The element '" + txt + "' on the page '" + screenname + "' was successfully verified sucessfully against the expected value '" + tdata[1] + "'";
865						 		    	}else{
866	                                        global.status = "Fail";global.eventStatus="fail"
867								            global.msg = "The element '" + txt + "' on the page '" + screenname + "' was successfully not verified against the expected value '" + tdata[1] + "'";
868						        	  	}
869						        	  }
870						        	}
871                                }else {
872						          
873						       	  //var arr=await driver.elements(selector_type,selector_val)
874						       	 //  console.log("ENterrrrr",arr.length)
875									var d2=await scrollToFindElement('xpath',"//android.widget.TextView[@text='"+tdata[0]+"']",tdata[0],'up','verify')
876									 console.log('d2', d2)
877						       	if(d2) 	{
878                                   console.log("//*[@text='"+ tdata[0]+"']/following-sibling::"+selectorval)
879                                   var flag1=false;						                
880						           var selector3 = await driver.elements("xpath","//*[@text='"+ tdata[0]+"']/following-sibling::"+selectorval)
881						           console.log(selector3.length)
882						           if(selector3.length==0){
883						                 	global.status = "Fail";global.eventStatus="fail"
884								             global.msg = "The element '" + txt + "' on the page '" + screenname + "' was successfully not verified against the expected value '" + tdata[1] + "'";
885						           }
886						           for(var ins in selector3)	{
887
888						        	  var txt;
889						        	  txt= tdata[1].substring(0,1)=='#' ? await driver.getAttribute(selector3[ins],'resourceId') : await selector3[ins].text() ;
890						        	  var datas=tdata[1].substring(0,1)=='#' ? tdata[1].substring(1) : tdata[1];
891
892						        	  if(txt==datas )	  { 	flag1=true;console.log("success: ",txt)     	  }
893						        	  if(ins==selector3.length-1)	  {
894						        	  	if(flag1){
895                                            global.status = "Pass";global.eventStatus="success"
896								            global.msg = "The element '" + txt + "' on the page '" + screenname + "' was successfully verified sucessfully against the expected value '" + tdata[1] + "'";
897						 		    	}else{
898	                                        global.status = "Fail";global.eventStatus="fail"
899											global.msg = "The element '" + txt + "' on the page '" + screenname + "' was successfully not verified against the expected value '" + tdata[1] + "'";
900						        	  	}
901						        	  }
902						        	}
903						       	}else { 
904                                           global.status = "Fail";global.eventStatus="fail"
905										   global.msg = "The element '" + txt + "' on the page '" + screenname + "' was successfully not verified against the expected value '" + tdata[1] + "'";
906						       	}						       						       	
907						       }
908						      // d=await delay();
909					break;	
910					
911                    case "text":
912						e1 = await driver.elementOrNull(selector_type,selector_val)
913						//console.log(e1)
914						if (e1 === null){
915									console.log(fieldname," not found...waiting for 10 seconds")									
916									e1 = await driver.elementOrNull(selector_type,selector_val)
917									//await driver.setImplicitWaitTimeout(5000)
918									if (e1 === null){
919										global.status = "Fail";global.eventStatus="fail"
920										global.msg = "ERROR: Unable to find the value '" + fieldname + "' in the ' " + screenname + "' page." ;
921										//console.log(global.msg)										
922									}	else{	
923										var testdata = testdata.split(",")
924										var txt = await driver.getAttribute(e1,'text')
925											
926										var txt1=txt.replace(/\s/g,""); 
927										//var txt1=txt.replace(/^\s+|\s+$/g,' ');
928									     var txt2= txt1.includes(testdata);
929                                        
930										console.log(txt2, "..after wait")
931										//if (txt === testdata){
932											if (txt2){
933										global.status = "Pass";global.eventStatus="success"
934										global.msg = "The element'" + fieldname + "' on the page '" + screenname + "' displays the expected value '" + testdata;
935										//console.log(global.msg)
936										}else{
937										global.status = "Fail";global.eventStatus="fail"
938										global.msg = "The element'" + fieldname + "' on the page '" + screenname + "' does not display the expected value '"+ testdata;
939										}
940									}
941								}
942						else{		
943							var txt = await driver.getAttribute(e1,'text')
944										//var txt1=txt.replace(/\s/g,"");
945										var txt1=txt; 
946								//var txt1=txt.replace(/^\s+|\s+$/g,' ');
947								var txt2= txt1.includes(testdata);
948							console.log(txt2, ".. no wait",txt1)
949							if (txt2 ){
950							console.log(txt2, " has passed...")
951							global.status = "Pass";global.eventStatus="success"
952							global.msg = "The element'" + fieldname + "' on the page '" + screenname + "' displays the correct value";
953							}else{
954							global.status = "Fail";global.eventStatus="fail"
955							global.msg = "The element'" + fieldname + "' on the page '" + screenname + "' does  not display the correct value";
956							}
957						}
958
959                    d=await delay()
960					break;
961					
962                   
963				 	default:
964                    global.status = "Fail";
965					global.msg = "Fail:Incorrect Type '"+type+"' in Verify keyword.Please check...";
966				 	break;
967
968				  }
969		break;	
970     
971		case "isdisplayed":
972		
973		switch (type)
974		{
975			case "text":
976					try
977					   {
978						   console.log("inside isdisplayed")
979						   /*const iscroll = Selector(stepdata[i].selector)
980						   await t.eval(() => scroll().scrollIntoView(), {dependencies: {iscroll}})*/
981						   await driver.elementIfExists(selector_type,selector_val,function(err,el){
982							 if (err){
983								 console.log("Element was NOT found... ")
984								 global.status = "Fail";global.eventStatus="fail"
985								 global.msg = "ERROR: Unable to find the element '" + fieldname + "' in the ' " + screenname + "' page. SYSTEM ERROR: " + err;
986							 }
987							 else{
988								 console.log("Element was found... ")
989								global.status = "Pass";global.eventStatus="success"
990							  global.msg = "The element '" + fieldname + "' on the page '" + screenname + "' was identified";
991							 }
992						   })
993						   //console.log(stepdata[i].stepno,"isDisplayed",stepdata[i].expected)
994						 
995					   } catch(err)
996						 {
997						   //console.log(stepdata[i].stepno,"Fail",err.type);
998						         console.log("Element was NOT found... ")
999								 global.status = "Fail";global.eventStatus="fail"
1000								 global.msg = "ERROR: Unable to find the element '" + fieldname + "' in the ' " + screenname + "' page. SYSTEM ERROR: " + err;
1001							 
1002						  
1003						 }
1004		d=await delay()
1005		break;
1006
1007		case "tabletext":
1008		
1009			var tdata=testdata.split(/>>(.*)/);
1010			
1011			var d2= await driver.elementOrNull('xpath',"//android.widget.TextView[@text='"+ tdata[0]+"']")
1012			if(d2)
1013			{
1014			console.log("//*[@text='"+ tdata[0]+"']/following-sibling::android.widget.TextView")
1015			var flag1=false;						                
1016			var selector3 = await driver.elements("xpath","//*[@text='"+ tdata[0]+"']/following-sibling::"+selectorval)
1017			console.log(selector3.length)
1018			if(selector3.length==0){
1019					  global.status = "Fail";global.eventStatus="fail"
1020					 global.msg = "The field '" + fieldname + "' on the page '" + screenname + "' was successfully not displayed";
1021			}
1022			for(var ins in selector3)
1023			 {
1024				 var txt=await selector3[ins].text()
1025			   if((txt!="")||(txt!=null)) 	  { 	flag1=true;console.log("success: ",txt)     	  }
1026			   if(ins==selector3.length-1)
1027			   {
1028				   if(flag1){
1029					 global.status = "Pass";global.eventStatus="success"
1030					 global.msg = "The element '" + txt + "' on the page '" + screenname + "' was successfully displayed";
1031				  }else{
1032					 global.status = "Fail";global.eventStatus="fail"
1033					 global.msg = "The field '" + fieldname + "' on the page '" + screenname + "' was successfully not displayed";
1034				  
1035				   }
1036			   }
1037			 }
1038			}else { 
1039				var scrollelm=await scrollToFindElement('xpath',"//android.widget.TextView[@text='"+tdata[0]+"']",tdata[0],'up','verify')
1040					if(scrollelm) {
1041						console.log("//*[@text='"+ tdata[0]+"']/following-sibling::android.widget.TextView")
1042			var flag1=false;						                
1043			var selector3 = await driver.elements("xpath","//*[@text='"+ tdata[0]+"']/following-sibling::"+selectorval)
1044			console.log(selector3.length)
1045			if(selector3.length==0){
1046					  global.status = "Fail";global.eventStatus="fail"
1047					 global.msg = "The field '" + fieldname + "' on the page '" + screenname + "' was successfully not displayed";
1048			}
1049			for(var ins in selector3)
1050			 {
1051				 var txt=await selector3[ins].text()
1052			   if((txt!="")||(txt!=null)) 	  { 	flag1=true;console.log("success: ",txt)     	  }
1053			   if(ins==selector3.length-1)
1054			   {
1055				   if(flag1){
1056					 global.status = "Pass";global.eventStatus="success"
1057					 global.msg = "The element '" + txt + "' on the page '" + screenname + "' was successfully displayed";
1058				  }else{
1059					 global.status = "Fail";global.eventStatus="fail"
1060					 global.msg = "The field '" + fieldname + "' on the page '" + screenname + "' was successfully not displayed";
1061				  
1062				   }
1063			   }
1064			 }
1065					} else { 
1066					global.status = "Fail";global.eventStatus="fail"
1067					global.msg = "The field '" + fieldname + "' on the page '" + screenname + "' was successfully not displayed";
1068			}	
1069		}					       						       	
1070		
1071	   // d=await delay();
1072break;
1073
1074default:
1075global.status = "Fail";
1076global.msg = "Fail:Incorrect verify Type.Please check test step";
1077break;
1078
1079}
1080break;
1081
1082case "retrieve":
1083		
1084		switch (type)
1085		{
1086			case "text":
1087					
1088						   console.log("inside retrieve")
1089						   /*const iscroll = Selector(stepdata[i].selector)
1090						   await t.eval(() => scroll().scrollIntoView(), {dependencies: {iscroll}})*/
1091						   await driver.elementIfExists(selector_type,selector_val,function(err,el){
1092							if (e1 === null){
1093								global.status = "Fail";global.eventStatus="fail"
1094								global.msg = "ERROR: Unable to retrieve the value '" + fieldname + "' in the ' " + screenname + "' page." ;
1095								//console.log(global.msg)										
1096							}	else{	
1097								var txt =  driver.getAttribute(e1,'text')
1098								var retdata2 = testdata.split("||");
1099								var retdata = retdata2[1]
1100								retdata = txt;
1101								global.status = "Pass";global.eventStatus="success"
1102								global.msg = "The element '" + retdata + "' on the page '" + screenname + "' was successfully retrieved";
1103
1104							}
1105						});
1106					  
1107		d=await delay()
1108		break;
1109
1110		case "tabletext":
1111
1112
1113			var retdata2 = testdata.split("||");
1114			var retdata = retdata2[1]			 
1115			var tdata=retdata.split(/>>(.*)/);
1116			
1117			var d2= await driver.elementOrNull('xpath',"//android.widget.TextView[@text='"+ tdata[0]+"']")
1118			if(d2)
1119			{
1120			console.log("//*[@text='"+ tdata[0]+"']/following-sibling::android.widget.TextView")
1121			var flag1=false;						                
1122			var selector3 = await driver.elements("xpath","//*[@text='"+ tdata[0]+"']/following-sibling::"+selectorval)
1123			console.log(selector3.length)
1124			if(selector3.length==0){
1125					  global.status = "Fail";global.eventStatus="fail"
1126					 global.msg = "The field '" + fieldname + "' on the page '" + screenname + "' was successfully not retrieved";
1127			}
1128			for(var ins in selector3)
1129			 {
1130				 var txt=await selector3[ins].text()
1131			   if((txt!="")||(txt!=null)) 	  { 	flag1=true;console.log("success: ",txt)     	  }
1132			   if(ins==selector3.length-1)
1133			   {
1134				   if(flag1){
1135					   tdata[1] = txt;
1136					 global.status = "Pass";global.eventStatus="success"
1137					 global.msg = "The element '" + txt + "' on the page '" + screenname + "' was successfully retrieved";
1138				  }else{
1139					 global.status = "Fail";global.eventStatus="fail"
1140					 global.msg = "The field '" + fieldname + "' on the page '" + screenname + "' was successfully not retrieved";
1141				  
1142				   }
1143			   }
1144			 }
1145			}else { 
1146					global.status = "Fail";global.eventStatus="fail"
1147					global.msg = "The field '" + fieldname + "' on the page '" + screenname + "' was successfully not displayed";
1148			}						       						       	
1149		
1150	   // d=await delay();
1151break;
1152
1153default:
1154global.status = "Fail";
1155global.msg = "Fail:Incorrect verify Type.Please check test step";
1156break;
1157
1158}
1159break;
1160
1161
1162		case "longpress":
1163						 try {
1164		el = selectorval;
1165		var cl_el =   el+ testdata+"']";
1166					 console.log(cl_el , "cl_el inside click")
1167				
1168					 var click_ele = await driver.elementOrNull('xpath', cl_el)
1169					 console.log("click_ele", click_ele);
1170					 let action = new wd.TouchAction(driver);
1171					 action.longPress({el: click_ele});																		
1172						await action.perform();
1173					 
1174					 console.log("Element was found... ")
1175					global.status = "Pass";global.eventStatus="success"
1176				  global.msg = "The element '" + fieldname + "' on the page '" + screenname + "' was long pressed";
1177				 
1178				} catch(err)
1179				{
1180				  //console.log(stepdata[i].stepno,"Fail",err.type);
1181						console.log("Element was NOT found... ")
1182						global.status = "Fail";global.eventStatus="fail"
1183						global.msg = "ERROR: Unable to long press the element '" + fieldname + "' in the ' " + screenname + "' page. SYSTEM ERROR: " + err;
1184					
1185				 
1186				}
1187d=await delay()
1188break;
1189
1190
1191case "click":
1192		try
1193		   {
1194			   /*const iscroll = Selector(stepdata[i].selector)
1195			   await t.eval(() => scroll().scrollIntoView(), {dependencies: {iscroll}})*/
1196			   el = selectorval;
1197
1198					// console.log("Element was NOT found... ")
1199					// global.status = "Fail";global.eventStatus="fail"
1200					// global.msg = "ERROR: Unable to Click the element '" + fieldname + "' in the ' " + screenname + "' page. SYSTEM ERROR: " + err;
1201					 var cl_el =   el+ testdata+"']";
1202					 console.log(cl_el , "cl_el inside click")
1203				
1204					 var click_ele = await driver.elementOrNull('xpath', cl_el)
1205					 console.log("click_ele", click_ele);
1206					  driver.clickElement(click_ele)
1207					 console.log("Element was found... ")
1208					global.status = "Pass";global.eventStatus="success"
1209				  global.msg = "The element '" + fieldname + "' on the page '" + screenname + "' was clicked";
1210				 
1211			 
1212			   //console.log(stepdata[i].stepno,"isDisplayed",stepdata[i].expected)
1213			 
1214		  } catch(err)
1215			 {
1216			   //console.log(stepdata[i].stepno,"Fail",err.type);
1217				     console.log("Element was NOT found... ")
1218					 global.status = "Fail";global.eventStatus="fail"
1219					 global.msg = "ERROR: Unable to Click the element '" + fieldname + "' in the ' " + screenname + "' page. SYSTEM ERROR: " + err;
1220				 
1221			  
1222			 }
1223d=await delay()
1224break;
1225
1226		default:
1227		global.status = "Fail";
1228		global.msg = "Fail:Incorrect Keyword '"+keyword+"'.Please check...";
1229		break;		  
1230}				
1231/* ------------------------------------------switch case end here----------------------------------------------------*/
1232}
1233
Full Screen