Best JavaScript code snippet using appium
commonActions.js
Source:commonActions.js  
...369    alias += random.charAt(Math.floor(Math.random() * random.length))370  await(await page[method]()).setValue(alias)371})372When('user toggle airplane mode', async () => {373  await driver.toggleData()374  await driver.toggleWiFi()375})376When('Whatsapp is in foreground', async () => {377  const state = await driver.queryAppState('com.whatsapp')378  if (state == 4) {379    console.log('Whatsapp is on Foreground')380  } else {381    throw new Error('Whatsapp is not running in foreground')382  }383})384When('Store is in foreground', async () => {385  const state = await driver.queryAppState('com.android.vending')386  if (state == 4) {387    console.log('Store is on Foreground')388  } else {389    throw new Error('Store is not running in foreground')390  }391})392When('return Banco del Sol App', async () => {393  await driver.background(-1)394  console.log('Current APP was closed')395  await driver.activateApp('ar.com.bdsol.bds.integration')396  console.log('return to BDS APP')397})398When('terminateApp and activateApp', async () => {399  //Reopen APP maintaining user link400  await driver.terminateApp('ar.com.bdsol.bds.integration')401  console.log('Current APP was closed')402  await driver.activateApp('ar.com.bdsol.bds.integration')403  console.log('return to BDS APP')404})405When('user set BS or local network conditions to {string}', async networkCondition => {406  const isLocal = browser.config.local407  if (isLocal == 'no') {408    //pass to browserstack predefine especific netorkprofile, see BS docs.409    if (driver.isIOS == true && networkCondition == 'airplane-mode')  {410      await updateBsAirplaneMode('no-network')411    } else {412      await updateBsAirplaneMode(networkCondition)413    } 414  } else {415    await driver.toggleData()416    await driver.toggleWiFi()417    //pause set to wait until wifi is online again418    await browser.pause(10000)419  }420  if (networkCondition == '4g-lte-good')  {421    console.log("Waiting return signal.")422    await browser.pause(20000)423  }424  425})426When('browser is in foreground', async () => {427    const state = await driver.queryAppState('com.android.chrome')428  if (state == 4) {429    console.log('Browser is on Foreground')...Appium JS commands.js
Source:Appium JS commands.js  
...230driver.toggleAirplaneMode();231// wd example232await driver.toggleAirplaneMode();233// webdriver.io example234driver.toggleData();235// wd example236await driver.toggleData();237// webdriver.io example238driver.toggleWiFi();239// wd example240await driver.toggleWiFi();241//PerformanceData242// webdriver.io example243driver.getPerformanceData('my.app.package', 'cpuinfo', 5);244// wd example245await driver.getPerformanceData('my.app.package', 'cpuinfo', 5);246// webdriver.io example247driver.getPerformanceDataTypes();248// wd example249await driver.getSupportedPerformanceDataTypes();250//ScreenRecording...java.js
Source:java.js  
...162  codeFor_toggleAirplaneMode () {163    return `driver.toggleAirplaneMode();`;164  }165  codeFor_toggleData () {166    return `driver.toggleData();`;167  }168  codeFor_toggleWiFi () {169    return `driver.toggleWifi();`;170  }171  codeFor_toggleLocationServices () {172    return `driver.toggleLocationServices();`;173  }174  codeFor_sendSMS (varNameIgnore, varIndexIgnore, phoneNumber, text) {175    return `driver.sendSMS("${phoneNumber}", "${text}");`;176  }177  codeFor_gsmCall (varNameIgnore, varIndexIgnore, phoneNumber, action) {178    return `driver.makeGsmCall("${phoneNumber}", "${action}");`;179  }180  codeFor_gsmSignal (varNameIgnore, varIndexIgnore, signalStrength) {...network-specs.js
Source:network-specs.js  
...110    it('should toggle data', async () => {111      adb.isDataOn.returns(false);112      driver.isEmulator.returns('is_emu');113      adb.setWifiAndData.returns('');114      await driver.toggleData();115      adb.setWifiAndData.calledWithExactly({data: true}, 'is_emu')116        .should.be.true;117    });118  });119  describe('toggleWiFi', () => {120    it('should toggle wifi', async () => {121      adb.isWifiOn.returns(false);122      driver.isEmulator.returns('is_emu');123      adb.setWifiAndData.returns('');124      await driver.toggleWiFi();125      adb.setWifiAndData.calledWithExactly({wifi: true}, 'is_emu')126        .should.be.true;127    });128  });...js-wdio.js
Source:js-wdio.js  
...135  codeFor_toggleAirplaneMode () {136    return `await driver.toggleAirplaneMode();`;137  }138  codeFor_toggleData () {139    return `await driver.toggleData();`;140  }141  codeFor_toggleWiFi () {142    return `await driver.toggleWiFi();`;143  }144  codeFor_toggleLocationServices () {145    return `await driver.toggleLocationServices();`;146  }147  codeFor_sendSMS () {148    return `// Not supported: sendSms;`;149  }150  codeFor_gsmCall () {151    return `// Not supported: gsmCall`;152  }153  codeFor_gsmSignal () {...js-wd.js
Source:js-wd.js  
...127  codeFor_toggleAirplaneMode () {128    return `await driver.toggleAirplaneMode();`;129  }130  codeFor_toggleData () {131    return `await driver.toggleData();`;132  }133  codeFor_toggleWiFi () {134    return `await driver.toggleWiFi();`;135  }136  codeFor_toggleLocationServices () {137    return `await driver.toggleLocationServices();`;138  }139  codeFor_sendSMS (varNameIgnore, varIndexIgnore, phoneNumber, text) {140    return `await driver.sendSms('${phoneNumber}', '${text}');`;141  }142  codeFor_gsmCall (varNameIgnore, varIndexIgnore, phoneNumber, action) {143    return `await driver.gsmCall('${phoneNumber}', '${action}');`;144  }145  codeFor_gsmSignal (varNameIgnore, varIndexIgnore, signalStrength) {...js-oxygen.js
Source:js-oxygen.js  
1import Framework from './framework';2class JsOxygenFramework extends Framework {3  get language () {4    return 'js';5  }6  wrapWithBoilerplate (code) {7    let caps = JSON.stringify(this.caps);8    let url = JSON.stringify(`${this.scheme}://${this.host}:${this.port}${this.path}`);9    return `// Requires the Oxygen HQ client library10// (npm install oxygen-cli -g)11// Then paste this into a .js file and run with:12// oxygen <file>.js13mob.init(${caps}, ${url});14${code}15`;16  }17  codeFor_findAndAssign (strategy, locator, localVar, isArray) {18    // wdio has its own way of indicating the strategy in the locator string19    switch (strategy) {20      case 'xpath': break; // xpath does not need to be updated21      case 'accessibility id': locator = `~${locator}`; break;22      case 'id': locator = `id=${locator}`; break;23      case 'name': locator = `name=${locator}`; break;24      case 'class name': locator = `css=${locator}`; break;25      case '-android uiautomator': locator = `android=${locator}`; break;26      case '-android datamatcher': locator = `android=${locator}`; break;27      case '-ios predicate string': locator = `ios=${locator}`; break;28      case '-ios class chain': locator = `ios=${locator}`; break; // TODO: Handle IOS class chain properly. Not all libs support it. Or take it out29      default: throw new Error(`Can't handle strategy ${strategy}`);30    }31    if (isArray) {32      return `let ${localVar} = mob.findElements(${JSON.stringify(locator)});`;33    } else {34      return `let ${localVar} = mob.findElement(${JSON.stringify(locator)});`;35    }36  }37  codeFor_click (varName, varIndex) {38    return `mob.click(${this.getVarName(varName, varIndex)});`;39  }40  codeFor_clear (varName, varIndex) {41    return `mob.clear(${this.getVarName(varName, varIndex)});`;42  }43  codeFor_sendKeys (varName, varIndex, text) {44    return `mob.type(${this.getVarName(varName, varIndex)}, ${JSON.stringify(text)});`;45  }46  codeFor_back () {47    return `mob.back();`;48  }49  codeFor_tap (varNameIgnore, varIndexIgnore, x, y) {50    return `mob.tap(${x}, ${y});`;51  }52  codeFor_swipe (varNameIgnore, varIndexIgnore, x1, y1, x2, y2) {53    return `mob.swipeScreen(${x1}, ${y1}, ${x2}, ${y2});`;54  }55  codeFor_getCurrentActivity () {56    return `let activityName = mob.getCurrentActivity();`;57  }58  codeFor_getCurrentPackage () {59    return `let packageName = mob.getCurrentPackage();`;60  }61  codeFor_installAppOnDevice (varNameIgnore, varIndexIgnore, app) {62    return `mob.installApp('${app}');`;63  }64  codeFor_isAppInstalledOnDevice (varNameIgnore, varIndexIgnore, app) {65    return `let isAppInstalled = mob.isAppInstalled("${app}");`;66  }67  codeFor_launchApp () {68    return `mob.launchApp();`;69  }70  codeFor_backgroundApp (varNameIgnore, varIndexIgnore, timeout) {71    return `mob.driver().background(${timeout});`;72  }73  codeFor_closeApp () {74    return `mob.closeApp();`;75  }76  codeFor_resetApp () {77    return `mob.resetApp();`;78  }79  codeFor_removeAppFromDevice (varNameIgnore, varIndexIgnore, app) {80    return `mob.removeApp('${app}')`;81  }82  codeFor_getAppStrings (varNameIgnore, varIndexIgnore, language, stringFile) {83    return `let appStrings = mob.driver().getAppStrings(${language ? `${language}, ` : ''}${stringFile ? `"${stringFile}` : ''});`;84  }85  codeFor_getClipboard () {86    return `let clipboardText = mob.driver().getClipboard();`;87  }88  codeFor_setClipboard (varNameIgnore, varIndexIgnore, clipboardText) {89    return `mob.driver().setClipboard('${clipboardText}')`;90  }91  codeFor_pressKeycode (varNameIgnore, varIndexIgnore, keyCode, metaState, flags) {92    return `mob.driver().longPressKeyCode(${keyCode}, ${metaState}, ${flags});`;93  }94  codeFor_longPressKeycode (varNameIgnore, varIndexIgnore, keyCode, metaState, flags) {95    return `mob.driver().longPressKeyCode(${keyCode}, ${metaState}, ${flags});`;96  }97  codeFor_hideDeviceKeyboard () {98    return `mob.driver().hideKeyboard();`;99  }100  codeFor_isKeyboardShown () {101    return `//isKeyboardShown not supported`;102  }103  codeFor_pushFileToDevice (varNameIgnore, varIndexIgnore, pathToInstallTo, fileContentString) {104    return `mob.driver().pushFile('${pathToInstallTo}', '${fileContentString}');`;105  }106  codeFor_pullFile (varNameIgnore, varIndexIgnore, pathToPullFrom) {107    return `let data = mob.driver().pullFile('${pathToPullFrom}');`;108  }109  codeFor_pullFolder (varNameIgnore, varIndexIgnore, folderToPullFrom) {110    return `let data = mob.driver().pullFolder('${folderToPullFrom}');`;111  }112  codeFor_toggleAirplaneMode () {113    return `mob.driver().toggleAirplaneMode();`;114  }115  codeFor_toggleData () {116    return `mob.driver().toggleData();`;117  }118  codeFor_toggleWiFi () {119    return `mob.driver().toggleWiFi();`;120  }121  codeFor_toggleLocationServices () {122    return `mob.driver().toggleLocationServices();`;123  }124  codeFor_sendSMS () {125    return `// Not supported: sendSms;`;126  }127  codeFor_gsmCall () {128    return `// Not supported: gsmCall`;129  }130  codeFor_gsmSignal () {131    return `// Not supported: gsmSignal`;132  }133  codeFor_gsmVoice () {134    return `// Not supported: gsmVoice`;135  }136  codeFor_shake () {137    return `mob.shake();`;138  }139  codeFor_lock (varNameIgnore, varIndexIgnore, seconds) {140    return `mob.driver().lock(${seconds});`;141  }142  codeFor_unlock () {143    return `mob.driver().unlock();`;144  }145  codeFor_isLocked () {146    return `let isLocked = mob.driver().isLocked();`;147  }148  codeFor_rotateDevice (varNameIgnore, varIndexIgnore, x, y, radius, rotation, touchCount, duration) {149    return `mob.driver().rotateDevice(${x}, ${y}, ${radius}, ${rotation}, ${touchCount}, ${duration});`;150  }151  codeFor_getPerformanceData () {152    return `// Not supported: getPerformanceData`;153  }154  codeFor_getSupportedPerformanceDataTypes () {155    return `// Not supported: getSupportedPerformanceDataTypes`;156  }157  codeFor_performTouchId (varNameIgnore, varIndexIgnore, match) {158    return `mob.driver().touchId(${match});`;159  }160  codeFor_toggleTouchIdEnrollment (varNameIgnore, varIndexIgnore, enroll) {161    return `mob.driver().toggleEnrollTouchId(${enroll});`;162  }163  codeFor_openNotifications () {164    return `mob.driver().openNotifications();`;165  }166  codeFor_getDeviceTime () {167    return `let time = mob.getDeviceTime();`;168  }169  codeFor_fingerprint (varNameIgnore, varIndexIgnore, fingerprintId) {170    return `mob.driver().fingerPrint(${fingerprintId});`;171  }172  codeFor_sessionCapabilities () {173    return `let caps = mob.driver().capabilities;`;174  }175  codeFor_setPageLoadTimeout (varNameIgnore, varIndexIgnore, ms) {176    return `mob.driver().setTimeout({'pageLoad': ${ms}});`;177  }178  codeFor_setAsyncScriptTimeout (varNameIgnore, varIndexIgnore, ms) {179    return `mob.driver().setTimeout({'script': ${ms}});`;180  }181  codeFor_setImplicitWaitTimeout (varNameIgnore, varIndexIgnore, ms) {182    return `mob.driver().setTimeout({'implicit': ${ms}});`;183  }184  codeFor_setCommandTimeout () {185    return `// Not supported: setCommandTimeout`;186  }187  codeFor_getOrientation () {188    return `let orientation = mob.driver().getOrientation();`;189  }190  codeFor_setOrientation (varNameIgnore, varIndexIgnore, orientation) {191    return `mob.driver().setOrientation("${orientation}");`;192  }193  codeFor_getGeoLocation () {194    return `let location = mob.driver().getGeoLocation();`;195  }196  codeFor_setGeoLocation (varNameIgnore, varIndexIgnore, latitude, longitude, altitude) {197    return `mob.driver().setGeoLocation({latitude: ${latitude}, longitude: ${longitude}, altitude: ${altitude}});`;198  }199  codeFor_logTypes () {200    return `let logTypes = mob.driver().getLogTypes();`;201  }202  codeFor_log (varNameIgnore, varIndexIgnore, logType) {203    return `let logs = mob.driver().getLogs('${logType}');`;204  }205  codeFor_updateSettings (varNameIgnore, varIndexIgnore, settingsJson) {206    return `mob.driver().updateSettings(${settingsJson});`;207  }208  codeFor_settings () {209    return `let settings = mob.driver().getSettings();`;210  }211}212JsOxygenFramework.readableName = 'JS - Oxygen HQ';...sensor.test.js
Source:sensor.test.js  
...82           83        // await delay(2000);84        await driver.openNotifications();85        await delay(3000);86        await driver.toggleData();  87        await delay(3000);88        let status_Mdata_on = await (await sensorPage.Mdata_).getText()89        expect(status_Mdata_on).equal('On')90        console.log('turnedon data ')91        await delay(3000);92        await driver.toggleData();93        await delay(3000);94        let status_Mdata_off = await (await sensorPage.Mdata_).getText()95        expect(status_Mdata_off).equal('Off')96        console.log('turnedoff data ')97        await driver.back()98        99    });100    it(' location', async () => {101        // await delay(2000);102        await driver.openNotifications();103        await delay(2000);104        // await driver.toggleLocationServices();105        await (await sensorPage.location_).click()106        await delay(3000); ...Using AI Code Generation
1driver.toggleData();2driver.toggleAirplaneMode();3driver.toggleWifi();4driver.toggleLocationServices();5driver.launchApp();6driver.closeApp();7driver.resetApp();8driver.installApp();9driver.removeApp();10driver.activateApp();11driver.backgroundApp();12driver.endTestCoverage();13driver.startActivity();14driver.getCurrentPackage();15driver.getCurrentActivity();16driver.getDeviceTime();17driver.getSettings();18driver.updateSettings();19driver.getPerformanceData();20driver.getPerformanceDataTypes();21driver.isAppInstalled();22driver.isLocked();23driver.lock();Using AI Code Generation
1var driver = new wd.Builder()2    .withCapabilities({3    })4    .build();5    .elementByName('Add Contact')6    .click()7    .elementByName('Save')8    .click()9    .elementByName('Name')10    .sendKeys('Some Name')11    .elementByName('Save')12    .click()13    .elementByName('Add Contact')14    .click()15    .elementByName('Save')16    .click()17    .elementByName('Name')18    .sendKeys('Some Other Name')19    .elementByName('Save')20    .click()21    .elementByName('Some Name')22    .click()23    .elementByName('Edit')24    .click()25    .elementByName('Name')26    .sendKeys('Some New Name')27    .elementByName('Save')28    .click()29    .sleep(5000)30    .elementByName('Some New Name')31    .click()32    .elementByName('Delete')33    .click()34    .elementByName('OK')35    .click()36    .elementByName('Some Other Name')37    .click()38    .elementByName('Delete')39    .click()40    .elementByName('OK')41    .click()42    .sleep(1000)43    .quit();Using AI Code Generation
1driver.toggleData();2driver.toggleAirplaneMode();3driver.toggleWifi();4driver.toggleLocationServices();5driver.toggleWiFi();6driver.toggleData();7driver.toggleAirplaneMode();8driver.toggleWifi();9driver.toggleLocationServices();10driver.toggleWiFi();11driver.toggleData();Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
