Best JavaScript code snippet using appium-xcuitest-driver
driver.js
Source:driver.js  
...543    }544    if (this.isRealDevice()) {545      await this.installToRealDevice();546    } else {547      await this.installToSimulator();548    }549    if (util.hasValue(this.opts.iosInstallPause)) {550      // https://github.com/appium/appium/issues/6889551      let pause = parseInt(this.opts.iosInstallPause, 10);552      await B.delay(pause);553    }554  }555  async installToSimulator () {556    if (this.opts.fullReset && this.opts.bundleId) {557      log.debug('Full reset requested. Removing app from device');558      await removeApp(this.opts.device.udid, this.opts.bundleId);559    }560    log.debug(`Installing app '${this.opts.app}' on device`);561    await installApp(this.opts.device.udid, this.opts.app);...driver-specs.js
Source:driver-specs.js  
1import sinon from 'sinon';2import * as iosDriver from 'appium-ios-driver';3import { JWProxy } from 'appium-base-driver';4import XCUITestDriver from '../..';5import xcode from 'appium-xcode';6import _ from 'lodash';7import chai from 'chai';8import * as utils from '../../lib/utils';9import { MOCHA_LONG_TIMEOUT } from './helpers';10chai.should();11const expect = chai.expect;12const caps = {13  platformName: 'iOS',14  deviceName: 'iPhone 6',15  app: '/foo.app',16  platformVersion: '10.0',17};18describe('driver commands', function () {19  describe('status', function () {20    let driver;21    let jwproxyCommandSpy;22    beforeEach(function () {23      driver = new XCUITestDriver();24      // fake the proxy to WDA25      const jwproxy = new JWProxy();26      jwproxyCommandSpy = sinon.stub(jwproxy, 'command').callsFake(async function () { // eslint-disable-line require-await27        return {some: 'thing'};28      });29      driver.wda = {30        jwproxy,31      };32    });33    afterEach(function () {34      jwproxyCommandSpy.reset();35    });36    it('should not have wda status by default', async function () {37      const status = await driver.getStatus();38      jwproxyCommandSpy.calledOnce.should.be.false;39      expect(status.wda).to.be.undefined;40    });41    it('should return wda status if cached', async function () {42      driver.cachedWdaStatus = {};43      const status = await driver.getStatus();44      jwproxyCommandSpy.called.should.be.false;45      status.wda.should.exist;46    });47  });48  describe('createSession', function () {49    let driver;50    let sandbox;51    beforeEach(function () {52      driver = new XCUITestDriver();53      sandbox = sinon.createSandbox();54      sandbox.stub(driver, 'determineDevice').callsFake(async function () { // eslint-disable-line require-await55        return {56          device: {57            shutdown: _.noop,58            isRunning () {59              return true;60            },61            stat () {62              return {state: 'Booted'};63            },64            clearCaches: _.noop,65            getWebInspectorSocket () {66              return '/path/to/uds.socket';67            },68          },69          udid: null,70          realDevice: null71        };72      });73      sandbox.stub(driver, 'configureApp').callsFake(_.noop);74      sandbox.stub(driver, 'startLogCapture').callsFake(_.noop);75      sandbox.stub(driver, 'startSim').callsFake(_.noop);76      sandbox.stub(driver, 'startWdaSession').callsFake(_.noop);77      sandbox.stub(driver, 'startWda').callsFake(_.noop);78      sandbox.stub(driver, 'setReduceMotion').callsFake(_.noop);79      sandbox.stub(driver, 'installAUT').callsFake(_.noop);80      sandbox.stub(driver, 'connectToRemoteDebugger').callsFake(_.noop);81      sandbox.stub(iosDriver.settings, 'setLocale').callsFake(_.noop);82      sandbox.stub(iosDriver.settings, 'setPreferences').callsFake(_.noop);83      sandbox.stub(xcode, 'getMaxIOSSDK').callsFake(async () => '10.0'); // eslint-disable-line require-await84      sandbox.stub(utils, 'checkAppPresent').callsFake(_.noop);85      sandbox.stub(iosDriver.appUtils, 'extractBundleId').callsFake(_.noop);86    });87    afterEach(function () {88      sandbox.restore();89    });90    it('should include server capabilities', async function () {91      this.timeout(MOCHA_LONG_TIMEOUT);92      const resCaps = await driver.createSession(caps);93      resCaps[1].javascriptEnabled.should.be.true;94    });95    it('should call startLogCapture', async function () {96      const c = { ... caps };97      Object.assign(c, {skipLogCapture: false});98      this.timeout(MOCHA_LONG_TIMEOUT);99      const resCaps = await driver.createSession(c);100      resCaps[1].javascriptEnabled.should.be.true;101      driver.startLogCapture.called.should.be.true;102    });103    it('should not call startLogCapture', async function () {104      const c = { ... caps };105      Object.assign(c, {skipLogCapture: true});106      this.timeout(MOCHA_LONG_TIMEOUT);107      const resCaps = await driver.createSession(c);108      resCaps[1].javascriptEnabled.should.be.true;109      driver.startLogCapture.called.should.be.false;110    });111  });112});113describe('installOtherApps', function () {114  let driver = new XCUITestDriver();115  let sandbox;116  beforeEach(function () {117    sandbox = sinon.createSandbox();118  });119  afterEach(function () {120    sandbox.restore();121  });122  it('should skip install other apps on real devices', async function () {123    sandbox.stub(driver, 'isRealDevice');124    sandbox.stub(driver.helpers, 'parseCapsArray');125    driver.isRealDevice.returns(true);126    await driver.installOtherApps('/path/to/iosApp.app');127    driver.isRealDevice.calledOnce.should.be.true;128    driver.helpers.parseCapsArray.notCalled.should.be.true;129  });130  it('should install multiple apps from otherApps as string on simulators', async function () {131    const SimulatorManagementModule = require('../../lib/simulator-management');132    sandbox.stub(SimulatorManagementModule, 'installToSimulator');133    sandbox.stub(driver, 'isRealDevice');134    driver.isRealDevice.returns(false);135    driver.opts.noReset = false;136    driver.opts.device = 'some-device';137    driver.lifecycleData = {createSim: false};138    await driver.installOtherApps('/path/to/iosApp.app');139    driver.isRealDevice.calledOnce.should.be.true;140    SimulatorManagementModule.installToSimulator.calledOnce.should.be.true;141    SimulatorManagementModule.installToSimulator.calledWith(142      'some-device',143      '/path/to/iosApp.app',144      undefined, {noReset: false, newSimulator: false}145    ).should.be.true;146  });147  it('should install multiple apps from otherApps as JSON array on simulators', async function () {148    const SimulatorManagementModule = require('../../lib/simulator-management');149    sandbox.stub(SimulatorManagementModule, 'installToSimulator');150    sandbox.stub(driver, 'isRealDevice');151    driver.isRealDevice.returns(false);152    driver.opts.noReset = false;153    driver.opts.device = 'some-device';154    driver.lifecycleData = {createSim: false};155    await driver.installOtherApps('["/path/to/iosApp1.app","/path/to/iosApp2.app"]');156    driver.isRealDevice.calledOnce.should.be.true;157    SimulatorManagementModule.installToSimulator.calledWith(158      'some-device',159      '/path/to/iosApp1.app',160      undefined, {noReset: false, newSimulator: false}161    ).should.be.true;162    SimulatorManagementModule.installToSimulator.calledWith(163      'some-device',164      '/path/to/iosApp2.app',165      undefined, {noReset: false, newSimulator: false}166    ).should.be.true;167  });...simulator-management.js
Source:simulator-management.js  
1import path from 'path';2import { getSimulator } from 'appium-ios-simulator';3import { createDevice, getDevices, terminate } from 'node-simctl';4import { resetXCTestProcesses } from './utils';5import _ from 'lodash';6import log from './logger';7// returns sim for desired caps8async function createSim (caps, sessionId) {9  let name = `appiumTest-${sessionId}`;10  let udid = await createDevice(name, caps.deviceName, caps.platformVersion);11  return await getSimulator(udid);12}13async function getExistingSim (opts) {14  let devices = await getDevices(opts.platformVersion);15  for (let device of _.values(devices)) {16    if (device.name === opts.deviceName) {17      return await getSimulator(device.udid);18    }19  }20  return null;21}22async function runSimulatorReset (device, opts) {23  if (opts.noReset && !opts.fullReset) {24    // noReset === true && fullReset === false25    log.debug('Reset: noReset is on. Leaving simulator as is');26    return;27  }28  if (!device) {29    log.debug('Reset: no device available. Skipping');30    return;31  }32  if (opts.fullReset) {33    log.debug('Reset: fullReset is on. Cleaning simulator');34    // stop XCTest processes if running to avoid unexpected side effects35    await resetXCTestProcesses(device.udid, true);36    // The simulator process must be ended before we delete applications.37    await device.shutdown();38    await device.clean();39  } else if (opts.bundleId) {40    // Terminate the app under test if it is still running on Simulator41    // Termination is not needed if Simulator is not running42    if (await device.isRunning()) {43      if (device.xcodeVersion.major >= 8) {44        try {45          await terminate(device.udid, opts.bundleId);46        } catch (err) {47          log.warn(`Reset: failed to terminate Simulator application with id "${opts.bundleId}"`);48        }49      } else {50        await device.shutdown();51      }52    }53    if (opts.app) {54      log.info('Not scrubbing third party app in anticipation of uninstall');55      return;56    }57    const isSafari = (opts.browserName || '').toLowerCase() === 'safari';58    try {59      if (isSafari) {60        await device.cleanSafari();61      } else {62        await device.scrubCustomApp(path.basename(opts.app), opts.bundleId);63      }64    } catch (err) {65      log.warn(err.message);66      log.warn(`Reset: could not scrub ${isSafari ? 'Safari browser' : 'application with id "' + opts.bundleId + '"'}. Leaving as is.`);67    }68  }69}70async function installToSimulator (device, app, bundleId, noReset = true) {71  if (!app) {72    log.debug('No app path is given. Nothing to install.');73    return;74  }75  if (bundleId) {76    if (await device.isAppInstalled(bundleId)) {77      if (noReset) {78        log.debug(`App '${bundleId}' is already installed. No need to reinstall.`);79        return;80      }81      log.debug(`Reset requested. Removing app with id '${bundleId}' from the device`);82      await device.removeApp(bundleId);83    }84  }85  log.debug(`Installing '${app}' on Simulator with UUID '${device.udid}'...`);86  await device.installApp(app);87  log.debug('The app has been installed successfully.');88}...Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3    desiredCapabilities: {4    }5};6    .remote(options)7    .init()8    .then(function (client) {9        return client.installToSimulator('./test.app');10    })11    .then(function (client) {12        return client.end();13    })14    .catch(function (err) {15        console.log(err);16    });17var webdriverio = require('webdriverio');18var options = {19    desiredCapabilities: {20    }21};22    .remote(options)23    .init()24    .then(function (client) {25        return client.uninstallFromSimulator('com.company.app');26    })27    .then(function (client) {28        return client.end();29    })30    .catch(function (err) {31        console.log(err);32    });Using AI Code Generation
1const wd = require('wd');2const {exec} = require('child_process');3const serverConfig = {4};5const desiredCaps = {6};7const driver = wd.promiseChainRemote(serverConfig);8  .init(desiredCaps)9  .then(() => driver.installToSimulator('/Users/saikrishna/Downloads/UICatalog.app'))10  .then(() => driver.quit());11const wd = require('wd');12const {exec} = require('child_process');13const serverConfig = {14};15const desiredCaps = {Using AI Code Generation
1var wd = require('wd');2var caps = {3};4driver.init(caps).then(function() {5  return driver.installToSimulator('/Users/username/Downloads/UICatalog7.1.app');6}).then(function() {7  return driver.quit();8}).done();9var wd = require('wd');10var caps = {11};12driver.init(caps).then(function() {13  return driver.removeApp('com.example.apple-samplecode.UICatalog');14}).then(function() {15  return driver.quit();16}).done();17var wd = require('wd');18var caps = {19};20driver.init(caps).then(function() {21  return driver.terminateApp('com.example.apple-samplecode.UICatalog');22}).then(function() {23  return driver.quit();24}).done();25var wd = require('wd');26var caps = {27};Using AI Code Generation
1const wd = require('wd');2const path = require('path');3const assert = require('assert');4const xcodeConfigFile = path.resolve(__dirname, 'xcodeConfig.json');5const xcodeConfig = require(xcodeConfigFile);6const appPath = path.resolve(__dirname, 'sample.app');7async function main() {8  const driver = await wd.promiseChainRemote(appiumServerUrl);9  await driver.init({10  });11  const isInstalled = await driver.installToSimulator(appPath);12  assert.ok(isInstalled);13  console.log('App has been installed to the Simulator');14  await driver.quit();15}16main().catch((err) => {17  console.error(err);18  process.exit(1);19});20{21}22const wd = require('wd');23const path = require('path');24const assert = require('assert');25const xcodeConfigFile = path.resolve(__dirname, 'xcodeConfig.json');26const xcodeConfig = require(xcodeConfigFile);27const appPath = path.resolve(__dirname, 'sample.app');28describe('Test Suite', function () {29  let driver;30  before(async function () {31    driver = await wd.promiseChainRemote(appiumServerUrl);32    await driver.init({33    });34  });35  it('should install app to Simulator', async function () {36    const isInstalled = await driver.installToSimulator(appPath);37    assert.ok(isInstalled);38    console.log('App has been installed to the Simulator');39  });40  afterEach(asyncUsing AI Code Generation
1var desiredCaps = {2};3var driver = wd.promiseChainRemote("localhost", 4723);4driver.init(desiredCaps).then(function() {5    return driver.installApp("/Users/username/Downloads/MyApp.app");6}).then(function() {7    return driver.quit();8});9var desiredCaps = {10};11var driver = wd.promiseChainRemote("localhost", 4723);12driver.init(desiredCaps).then(function() {13    return driver.installToSimulator("/Users/username/Downloads/MyApp.app");14}).then(function() {15    return driver.quit();16});17var desiredCaps = {18};19var driver = wd.promiseChainRemote("localhost", 4723);20driver.init(desiredCaps).then(function() {21    return driver.installToRealDevice("/Users/username/Downloads/MyApp.app");22}).then(function() {23    return driver.quit();24});25[HTTP] --> POST /wd/hub/session/8c2e7cf4-4b4f-4d0f-9f6e-9b9a1d3c3e0e/appium/device/install_app {"appPath":"/Users/username/Downloads/MyApp.app"}26[debug] [MJSONWP] Calling AppiumDriver.installApp() with args: [Using AI Code Generation
1var wd = require('wd');2var desiredCapabilities = {3};4var driver = wd.promiseChainRemote('localhost', 4723);5driver.init(desiredCapabilities)6    .then(() => driver.installToSimulator())7    .then(() => driver.quit())8    .catch((e) => console.log(e));9var wd = require('wd');Using AI Code Generation
1const { exec } = require('child_process');2const appPath = '/Users/username/Documents/MyApp.app';3const driverPath = '/Users/username/Documents/appium-xcuitest-driver';4const command = `node ${driverPath}/build/lib/driver.js --app ${appPath} --udid 00008020-000D1E1A0C0C802E --install-to-simulator`;5exec(command, (error, stdout, stderr) => {6    if (error) {7        console.log(`error: ${error.message}`);8        return;9    }10    if (stderr) {11        console.log(`stderr: ${stderr}`);12        return;13    }14    console.log(`stdout: ${stdout}`);15});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!!
