Best JavaScript code snippet using appium-xcuitest-driver
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';...basic-e2e-specs.js
Source:basic-e2e-specs.js  
...124    afterEach(async () => {125      await driver.setOrientation('PORTRAIT');126    });127    it('should get the current orientation', async () => {128      let orientation = await driver.getOrientation();129      ['PORTRAIT', 'LANDSCAPE'].should.include(orientation);130    });131    it('should set the orientation', async function () {132      await driver.setOrientation('LANDSCAPE');133      (await driver.getOrientation()).should.eql('LANDSCAPE');134    });135    it('should be able to interact with an element in LANDSCAPE', async function () {136      await driver.setOrientation('LANDSCAPE');137      let el = await driver.elementByAccessibilityId('Buttons');138      await el.click();139      await driver.elementByAccessibilityId('Button').should.not.be.rejected;140      await driver.back();141    });142  });143  describe('window size', () => {144    it('should be able to get the current window size', async () => {145      let size = await driver.getWindowSize('current');146      size.width.should.be.a.number;147      size.height.should.be.a.number;...driver-e2e-specs.js
Source:driver-e2e-specs.js  
...55        let caps = _.defaults({56          orientation: initialOrientation57        }, UICATALOG_SIM_CAPS);58        await driver.init(caps);59        let orientation = await driver.getOrientation();60        orientation.should.eql(initialOrientation);61      }62      for (let orientation of ['LANDSCAPE', 'PORTRAIT']) {63        it(`should be able to start in a ${orientation} mode`, async function () {64          this.timeout(MOCHA_TIMEOUT);65          await runOrientationTest(orientation);66        });67      }68    });69    /* jshint ignore:end */70    describe('reset', () => {71      it.skip('default: creates sim and deletes it afterwards', async () => {72        let caps = UICATALOG_SIM_CAPS;73        await killAllSimulators();...sensor.test.js
Source:sensor.test.js  
...50        51        await delay(2000);52        await driver.startActivity(app_package,app_package_activity_setting_home )53        // expect(await(await sensorPage.connected).isDisplayed()).equal(true);54        let orientation = await driver.getOrientation();55        expect(orientation).equal('PORTRAIT');56        await delay(2000);57        await driver.setOrientation("LANDSCAPE");58        let orientation_1 = await driver.getOrientation();59        expect(orientation_1).equal('LANDSCAPE');60        await delay(2000);61        await driver.setOrientation("PORTRAIT");62        let a_orientation = await driver.getOrientation();63        expect(a_orientation).equal('PORTRAIT');64    });65    // it('airplane mode', async () => {66        67    //     await delay(2000);68    //     await driver.openNotifications();69    //     await delay(2000);70    //     await driver.toggleAirplaneMode();      71    //     await delay(3000);72    //     let status_airplane_on = await (await sensorPage.Airplane_).getText()73    //     expect(status_airplane_on).equal('On')74    //     console.log('turnedon airplane mode')75    //     await driver.toggleAirplaneMode();76    //     await delay(3000);...dialog.test.js
Source:dialog.test.js  
...15        dialog.dialogOkBtn.click()16    })17    it('Verify that the app adjust when orientation is switched', () => {18        driver.setOrientation('LANDSCAPE')19        console.log(driver.getOrientation())20        driver.pause(1000)   //ms21        driver.saveScreenshot('./screenshots/landscape.png')22        dialog.appBtn.click()23        driver.setOrientation('PORTRAIT')24        console.log(driver.getOrientation())25        driver.back()26        driver.saveScreenshot('./screenshots/portrait.png')27    })28    it('Verify Timeouts', () => {29        driver.setImplicitTimeout(1000)30        driver.setTimeouts(1000)31        driver.pause(1000)32    })33    it('Verify the repeat alarm options has attribute checked set to true when selected', () => {34        let isChecked, text;35        dialog.appBtn.click()36        dialog.alertDialogBtn.click()37        dialog.repeatAlarmBtn.click()38        console.log(dialog._weekdayCheckbox(0).getText())...general-tests.js
Source:general-tests.js  
...34      source.should.contain('<MockNavBar id="nav"');35    });36    // TODO do we want to test driver.pageIndex? probably not37    it('should get the orientation', async function () {38      (await driver.getOrientation()).should.equal('PORTRAIT');39    });40    it('should set the orientation to something valid', async function () {41      await driver.setOrientation('LANDSCAPE');42      (await driver.getOrientation()).should.equal('LANDSCAPE');43    });44    it('should not set the orientation to something invalid', async function () {45      await driver.setOrientation('INSIDEOUT')46              .should.eventually.be.rejectedWith(/Orientation must be/);47    });48    it('should get a screenshot', async function () {49      should.exist(await driver.takeScreenshot());50    });51    it('should set implicit wait timeout', async function () {52      await driver.setImplicitWaitTimeout(1000);53    });54    it('should not set invalid implicit wait timeout', async function () {55      await driver.setImplicitWaitTimeout('foo')56              .should.eventually.be.rejectedWith(/ms/);...orientation-e2e-specs.js
Source:orientation-e2e-specs.js  
...16      driver = await initDriver(Object.assign({}, APIDEMOS_CAPS, {17        appActivity: '.view.TextFields',18        orientation: 'PORTRAIT',19      }));20      await driver.getOrientation().should.eventually.eql('PORTRAIT');21    });22    it('should have landscape orientation if requested', async function () {23      driver = await initDriver(Object.assign({}, APIDEMOS_CAPS, {24        appActivity: '.view.TextFields',25        orientation: 'LANDSCAPE',26      }));27      await driver.getOrientation().should.eventually.eql('LANDSCAPE');28    });29    it('should have portrait orientation if nothing requested', async function () {30      driver = await initDriver(Object.assign({}, APIDEMOS_CAPS, {31        appActivity: '.view.TextFields',32      }));33      await driver.getOrientation().should.eventually.eql('PORTRAIT');34    });35  });36  describe('setting -', function () {37    before(async function () {38      driver = await initDriver(Object.assign({}, APIDEMOS_CAPS, {39        appActivity: '.view.TextFields'40      }));41    });42    after(async function () {43      await driver.quit();44    });45    it('should rotate screen to landscape', async function () {46      await driver.setOrientation('PORTRAIT');47      await B.delay(3000);48      await driver.setOrientation('LANDSCAPE');49      await B.delay(3000);50      await driver.getOrientation().should.eventually.become('LANDSCAPE');51    });52    it('should rotate screen to landscape', async function () {53      await driver.setOrientation('LANDSCAPE');54      await B.delay(3000);55      await driver.setOrientation('PORTRAIT');56      await B.delay(3000);57      await driver.getOrientation().should.eventually.become('PORTRAIT');58    });59    it('should not error when trying to rotate to portrait again', async function () {60      await driver.setOrientation('PORTRAIT');61      await B.delay(3000);62      await driver.setOrientation('PORTRAIT');63      await B.delay(3000);64      await driver.getOrientation().should.eventually.become('PORTRAIT');65    });66  });...sample.test.js
Source:sample.test.js  
...13        await dialog.passwordEntry("Actual Password");14        await dialog.okBtnClick();15    });16    it('Verify that the app adjust when orientation is switched', async () => {17        console.log("##############################  ORIENTATION : #################################  ", await driver.getOrientation());18        await driver.setOrientation("LANDSCAPE");19        await driver.saveScreenshot('./test-execution_report/mobile-ui/screenshot/landscape.png');20        await driver.setOrientation("PORTRAIT");21        await driver.saveScreenshot("./test-execution_report/mobile-ui/screenshot/portrait.png");22    });...Using AI Code Generation
1var webdriver = require('selenium-webdriver'),2    until = webdriver.until;3var driver = new webdriver.Builder()4    .forBrowser('selenium-webdriver')5    .build();6driver.getOrientation().then(function(orientation) {7    console.log(orientation);8});9driver.quit();Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3    .withCapabilities({4    })5    .build();6driver.getOrientation().then(function(orientation) {7    console.log("Current orientation: " + orientation);8});9driver.quit();10var webdriver = require('selenium-webdriver');11var driver = new webdriver.Builder()12    .withCapabilities({13    })14    .build();15driver.setOrientation("LANDSCAPE").then(function() {16    console.log("Orientation set to LANDSCAPE");17});18driver.quit();19var webdriver = require('selenium-webdriver');20var driver = new webdriver.Builder()21    .withCapabilities({22    })23    .build();24driver.hideKeyboard().then(function() {25    console.log("Keyboard hidden");26});27driver.quit();28var webdriver = require('selenium-webdriver');29var driver = new webdriver.Builder()30    .withCapabilities({31    })32    .build();Using AI Code Generation
1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5const expect = chai.expect;6const should = chai.should();7const desiredCaps = {8};9driver.init(desiredCaps)10  .then(() => {11    return driver.getOrientation();12  })13  .then(orientation => {14    console.log(orientation);15  })16  .catch(err => {17    console.log(err);18  });19const wd = require('wd');20const chai = require('chai');21const chaiAsPromised = require('chai-as-promised');22chai.use(chaiAsPromised);23const expect = chai.expect;24const should = chai.should();25const desiredCaps = {26};27driver.init(desiredCaps)28  .then(() => {29    return driver.setOrientation('PORTRAIT');30  })31  .then(() => {32    return driver.getOrientation();33  })34  .then(orientation => {35    console.log(orientation);36  })37  .catch(err => {38    console.log(err);39  });40const wd = require('wd');41const chai = require('chai');42const chaiAsPromised = require('chai-as-promised');43chai.use(chaiAsPromised);44const expect = chai.expect;45const should = chai.should();46const desiredCaps = {Using AI Code Generation
1const wd = require('wd');2driver.init({3}).then(function() {4  return driver.getOrientation();5}).then(function(orientation) {6  console.log('orientation is: ', orientation);7});8const wd = require('wd');9driver.init({10}).then(function() {11  return driver.setOrientation('LANDSCAPE');12}).then(function() {13  return driver.getOrientation();14}).then(function(orientation) {15  console.log('orientation is: ', orientation);16});17const wd = require('wd');18driver.init({Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3  desiredCapabilities: {4  }5};6var client = webdriverio.remote(options);7  .init()8  .getOrientation()9  .then(function(orientation) {10    console.log("Device orientation is: " + orientation);11  })12  .end();Using AI Code Generation
1const wd = require('wd');2const driver = wd.promiseChainRemote('localhost', 4723);3driver.init({4}).then(() => driver.getOrientation())5  .then((orientation) => console.log('Orientation is: ', orientation))6  .catch((err) => console.log('Error occurred: ', err));7const wd = require('wd');8const driver = wd.promiseChainRemote('localhost', 4723);9driver.init({10}).then(() => driver.setOrientation('LANDSCAPE'))11  .then(() => console.log('Orientation set to LANDSCAPE'))12  .catch((err) => console.log('Error occurred: ', err));13const wd = require('wd');14const driver = wd.promiseChainRemote('localhost', 4723);15driver.init({16}).then(() => driver.getGeoLocation())17  .then((location) => console.log('Location is: ', location))18  .catch((err) => console.log('Error occurred: ', err));19const wd = require('wd');20const driver = wd.promiseChainRemote('localhost', 4723);Using AI Code Generation
1const wd = require('wd');2const assert = require('assert');3const { asserters } = wd;4const capabilities = {5};6const driver = wd.promiseChainRemote('localhost', 4723);7driver.init(capabilities);8  .getOrientation()9  .then((orientation) => {10    console.log(orientation);11  });12driver.quit();13const wd = require('wd');14const assert = require('assert');15const { asserters } = wd;16const capabilities = {17};18const driver = wd.promiseChainRemote('localhost', 4723);19driver.init(capabilities);20  .getScreenOrientation()21  .then((orientation) => {22    console.log(orientation);23  });24driver.quit();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!!
