Best JavaScript code snippet using appium-xcuitest-driver
driver.js
Source:driver.js  
...298        if (!this.relaxedSecurityEnabled) {299          log.errorAndThrow(`Appium server must have relaxed security flag set in order ` +300                            `for 'shutdownOtherSimulators' capability to work`);301        }302        await shutdownOtherSimulators(this.opts.device);303      }304      this.localConfig = await iosSettings.setLocaleAndPreferences(this.opts.device, this.opts, this.isSafari(), async (sim) => {305        await shutdownSimulator(sim);306        // we don't know if there needs to be changes a priori, so change first.307        // sometimes the shutdown process changes the settings, so reset them,308        // knowing that the sim is already shut309        await iosSettings.setLocaleAndPreferences(sim, this.opts, this.isSafari());310      });311      // Cleanup of installd cache helps to save disk space while running multiple tests312      // without restarting the Simulator: https://github.com/appium/appium/issues/9410313      await this.opts.device.clearCaches('com.apple.mobile.installd.staging');314      await this.startSim();315      if (this.opts.customSSLCert) {316        if (await hasSSLCert(this.opts.customSSLCert, this.opts.udid)) {...simulator-management.js
Source:simulator-management.js  
1import path from 'path';2import { getSimulator } from 'appium-ios-simulator';3import { createDevice, getDevices, terminate, shutdown } from 'node-simctl';4import { resetXCTestProcesses } from './utils';5import _ from 'lodash';6import { retry } from 'asyncbox';7import log from './logger';8/**9 * Create a new simulator with `appiumTest-` prefix and return the object.10 *11 * @param {object} caps - Capability set by a user. The options available are:12 *   - `deviceName` - a name for the device13 *   - `platformVersion` - the version of iOS to use14 * @returns {object} Simulator object associated with the udid passed in.15 */16async function createSim (caps) {17  const appiumTestDeviceName = `appiumTest-${caps.deviceName}`;18  const udid = await createDevice(appiumTestDeviceName, caps.deviceName, caps.platformVersion);19  return await getSimulator(udid);20}21/**22 * Get a simulator which is already running.23 *24 * @param {object} opts - Capability set by a user. The options available are:25 *   - `deviceName` - a name for the device26 *   - `platformVersion` - the version of iOS to use27 * @returns {?object} Simulator object associated with the udid passed in. Or null if no device is running.28 */29async function getExistingSim (opts) {30  const devices = await getDevices(opts.platformVersion);31  const appiumTestDeviceName = `appiumTest-${opts.deviceName}`;32  let appiumTestDevice;33  for (const device of _.values(devices)) {34    if (device.name === opts.deviceName) {35      return await getSimulator(device.udid);36    }37    if (device.name === appiumTestDeviceName) {38      appiumTestDevice = device;39    }40  }41  if (appiumTestDevice) {42    log.warn(`Unable to find device '${opts.deviceName}'. Found '${appiumTestDevice.name}' (udid: '${appiumTestDevice.udid}') instead`);43    return await getSimulator(appiumTestDevice.udid);44  }45  return null;46}47async function shutdownSimulator (device) {48  // stop XCTest processes if running to avoid unexpected side effects49  await resetXCTestProcesses(device.udid, true);50  await device.shutdown();51}52async function runSimulatorReset (device, opts) {53  if (opts.noReset && !opts.fullReset) {54    // noReset === true && fullReset === false55    log.debug('Reset: noReset is on. Leaving simulator as is');56    return;57  }58  if (!device) {59    log.debug('Reset: no device available. Skipping');60    return;61  }62  if (opts.fullReset) {63    log.debug('Reset: fullReset is on. Cleaning simulator');64    await shutdownSimulator(device);65    let isKeychainsBackupSuccessful = false;66    if (opts.keychainsExcludePatterns || opts.keepKeyChains) {67      isKeychainsBackupSuccessful = await device.backupKeychains();68    }69    await device.clean();70    if (isKeychainsBackupSuccessful) {71      await device.restoreKeychains(opts.keychainsExcludePatterns || []);72      log.info(`Successfully restored keychains after full reset`);73    } else if (opts.keychainsExcludePatterns || opts.keepKeyChains) {74      log.warn('Cannot restore keychains after full reset, because ' +75               'the backup operation did not succeed');76    }77  } else if (opts.bundleId) {78    // Terminate the app under test if it is still running on Simulator79    // Termination is not needed if Simulator is not running80    if (await device.isRunning()) {81      if (device.xcodeVersion.major >= 8) {82        try {83          await terminate(device.udid, opts.bundleId);84        } catch (err) {85          log.warn(`Reset: failed to terminate Simulator application with id "${opts.bundleId}"`);86        }87      } else {88        await shutdownSimulator(device);89      }90    }91    if (opts.app) {92      log.info('Not scrubbing third party app in anticipation of uninstall');93      return;94    }95    const isSafari = (opts.browserName || '').toLowerCase() === 'safari';96    try {97      if (isSafari) {98        await device.cleanSafari();99      } else {100        await device.scrubCustomApp(path.basename(opts.app), opts.bundleId);101      }102    } catch (err) {103      log.warn(err.message);104      log.warn(`Reset: could not scrub ${isSafari ? 'Safari browser' : 'application with id "' + opts.bundleId + '"'}. Leaving as is.`);105    }106  }107}108async function installToSimulator (device, app, bundleId, noReset = true) {109  if (!app) {110    log.debug('No app path is given. Nothing to install.');111    return;112  }113  if (bundleId) {114    if (await device.isAppInstalled(bundleId)) {115      if (noReset) {116        log.debug(`App '${bundleId}' is already installed. No need to reinstall.`);117        return;118      }119      log.debug(`Reset requested. Removing app with id '${bundleId}' from the device`);120      await device.removeApp(bundleId);121    }122  }123  log.debug(`Installing '${app}' on Simulator with UUID '${device.udid}'...`);124  // on Xcode 10 sometimes this is too fast and it fails125  await retry(2, device.installApp.bind(device), app);126  log.debug('The app has been installed successfully.');127}128async function shutdownOtherSimulators (currentDevice) {129  const allDevices = _.flatMap(_.values(await getDevices()));130  const otherBootedDevices = allDevices.filter((device) => device.udid !== currentDevice.udid && device.state === 'Booted');131  if (_.isEmpty(otherBootedDevices)) {132    log.info('No other running simulators have been detected');133    return;134  }135  log.info(`Detected ${otherBootedDevices.length} other running Simulator${otherBootedDevices.length === 1 ? '' : 's'}.` +136           `Shutting ${otherBootedDevices.length === 1 ? 'it' : 'them'} down...`);137  for (const {udid} of otherBootedDevices) {138    // It is necessary to stop the corresponding xcodebuild process before killing139    // the simulator, otherwise it will be automatically restarted140    await resetXCTestProcesses(udid, true);141    await shutdown(udid);142  }143}144export { createSim, getExistingSim, runSimulatorReset, installToSimulator,...desired-caps.js
Source:desired-caps.js  
1import _ from 'lodash';2import { desiredCapConstraints as iosDesiredCapConstraints } from 'appium-ios-driver';3let desiredCapConstraints = _.defaults({4  showXcodeLog: {5    isBoolean: true6  },7  wdaLocalPort: {8    isNumber: true9  },10  iosInstallPause: {11    isNumber: true12  },13  xcodeConfigFile: {14    isString: true15  },16  xcodeOrgId: {17    isString: true18  },19  xcodeSigningId: {20    isString: true21  },22  keychainPath: {23    isString: true24  },25  keychainPassword: {26    isString: true27  },28  bootstrapPath: {29    isString: true30  },31  agentPath: {32    isString: true33  },34  tapWithShortPressDuration: {35    isNumber: true36  },37  scaleFactor: {38    isString: true39  },40  usePrebuiltWDA: {41    isBoolean: true42  },43  customSSLCert: {44    isString: true45  },46  preventWDAAttachments: {47    isBoolean: true48  },49  webDriverAgentUrl: {50    isString: true51  },52  derivedDataPath: {53    isString: true54  },55  useNewWDA: {56    isBoolean: true57  },58  wdaLaunchTimeout: {59    isNumber: true60  },61  wdaConnectionTimeout: {62    isNumber: true63  },64  updatedWDABundleId: {65    isString: true66  },67  resetOnSessionStartOnly: {68    isBoolean: true69  },70  commandTimeouts: {71    // recognize the cap,72    // but validate in the driver#validateDesiredCaps method73  },74  wdaStartupRetries: {75    isNumber: true76  },77  wdaStartupRetryInterval: {78    isNumber: true79  },80  prebuildWDA: {81    isBoolean: true82  },83  connectHardwareKeyboard: {84    isBoolean: true85  },86  calendarAccessAuthorized: {87    isBoolean: true88  },89  startIWDP: {90    isBoolean: true,91  },92  useSimpleBuildTest: {93    isBoolean: true94  },95  waitForQuiescence: {96    isBoolean: true97  },98  maxTypingFrequency: {99    isNumber: true100  },101  nativeTyping: {102    isBoolean: true103  },104  simpleIsVisibleCheck: {105    isBoolean: true106  },107  useCarthageSsl: {108    isBoolean: true109  },110  shouldUseSingletonTestManager: {111    isBoolean: true112  },113  isHeadless: {114    isBoolean: true115  },116  webkitDebugProxyPort: {117    isNumber: true118  },119  useXctestrunFile: {120    isBoolean: true121  },122  absoluteWebLocations: {123    isBoolean: true124  },125  simulatorWindowCenter: {126    isString: true127  },128  useJSONSource: {129    isBoolean: true130  },131  shutdownOtherSimulators: {132    isBoolean: true133  },134  keychainsExcludePatterns: {135    isString: true136  },137  realDeviceScreenshotter: {138    isString: true,139    presence: false,140    inclusionCaseInsensitive: ['idevicescreenshot']141  },142  showSafariConsoleLog: {143    isBoolean: true144  },145  showSafariNetworkLog: {146    isBoolean: true147  },148  mjpegServerPort: {149    isNumber: true,150  }151}, iosDesiredCapConstraints);152export { desiredCapConstraints };...Using AI Code Generation
1const wdio = require('webdriverio');2const opts = {3    desiredCapabilities: {4    }5};6const client = wdio.remote(opts);7client.init().then(() => {8    return client.execute('mobile: shutdownOtherSimulators');9}).then(() => {10    return client.deleteSession();11}).catch((err) => {12    console.log(err);13});14info: [debug] [JSONWP Proxy] Got response with status 200: {"value":"Method 'POST' not supported","sessionId":"2B2A2C7F-5C5D-4F2E-9C5A-6D7E9D9C1C7B","status":9}Using AI Code Generation
1const wd = require('webdriverio');2const opts = {3    desiredCapabilities: {4    }5};6(async function main() {7    let client = await wd.remote(opts);8    await client.execute('mobile: shutdownOtherSimulators');9    await client.deleteSession();10})();Using AI Code Generation
1let driver = await wdio.remote({2    capabilities: {3    }4});5await driver.execute('shutdownOtherSimulators');6await driver.execute('mobile: launchApp', {bundleId: 'com.apple.Preferences'});7let driver = await wdio.remote({8    capabilities: {9    }10});11await driver.execute('shutdownOtherSimulators');12await driver.execute('mobile: launchApp', {bundleId: 'com.apple.Preferences'});13let driver = await wdio.remote({14    capabilities: {15    }16});17await driver.execute('shutdownOtherSimulators');18await driver.execute('mobile: launchApp', {bundleId: 'com.apple.Preferences'});19let driver = await wdio.remote({20    capabilities: {21    }22});23await driver.execute('shutdownOtherSimulators');24await driver.execute('mobile: launchApp', {bundleId: 'com.apple.Preferences'});25let driver = await wdio.remote({26    capabilities: {Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desired = {4};5var driver = wd.promiseChainRemote('localhost', 4723);6  .init(desired)7  .then(function () {8    return driver.shutdownOtherSimulators();9  })10  .then(function () {11    console.log("Simulator shutdown");12  })13  .fin(function() { return driver.quit(); })14  .done();Using AI Code Generation
1const wd = require('wd');2const {shutdownOtherSimulators} = require('appium-xcuitest-driver/lib/simulator-management.js');3async function main () {4  const driver = wd.promiseChainRemote();5  await driver.init({6  });7  await shutdownOtherSimulators(driver);8}9main();10const wd = require('wd');11const {shutdownOtherSimulators} = require('appium-xcuitest-driver/lib/simulator-management.js');12async function main () {13  const driver = wd.promiseChainRemote();14  await driver.init({15  });16  await shutdownOtherSimulators(driver);17}18main();Using AI Code Generation
1const wd = require('wd');2const { shutdownOtherSimulators } = require('appium-xcuitest-driver/lib/simulator-management.js');3const { DEFAULT_SIMULATOR_NAME } = require('appium-xcuitest-driver/lib/simulator-management.js');4const { getExistingSimulator } = require('appium-xcuitest-driver/lib/simulator-management.js');5const { createSim } = require('appium-xcuitest-driver/lib/simulator-management.js');6async function main () {7  await driver.init({Using AI Code Generation
1var shutdownOtherSimulators = require('./lib/appium-xcuitest-driver/lib/commands/shutdown-other-simulators');2var simulators = shutdownOtherSimulators.shutdownOtherSimulators;3simulators();4"use strict";5var _ = require('lodash'),6    B = require('bluebird'),7    logger = require('../logger'),8    simctl = require('node-simctl'),9    xcode = require('appium-xcode'),10    xcrun = require('appium-xcrun');11function getDevices (xcodeVersion) {12  return xcrun.getDevicesWithRetry(xcodeVersion)13    .then(function (devices) {14      return _.values(devices);15    });16}17function getSimulators (xcodeVersion) {18  return simctl.getDevices({xcodeVersion: xcodeVersion});19}20function getDevicesToShutDown (xcodeVersion) {21  return B.all([getDevices(xcodeVersion), getSimulators(xcodeVersion)])22    .then(function (devices) {23      var devicesToShutDown = [];24      _.each(_.flatten(devices), function (device) {25        if (!device.isAvailable) {26          devicesToShutDown.push(device.udid);27        }28      });29      return devicesToShutDown;30    });31}32function shutdownDevices (xcodeVersion) {33  return getDevicesToShutDown(xcodeVersion)34    .then(function (devices) {35      logger.debug(`Shutting down devices: ${devices}`);36      return B.map(devices, function (device) {37        return xcrun.shutdown(device);38      });39    });40}41function shutdownOtherSimulators () {42  return xcode.getVersion(true)43    .then(function (xcodeVersion) {44      return shutdownDevices(xcodeVersion);45    });46}47module.exports = { shutdownOtherSimulators: shutdownOtherSimulators };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!!
