Best JavaScript code snippet using appium-base-driver
driver.js
Source:driver.js
...974 `'${caps.platformVersion}' is given instead.`);975 }976 // additionalWebviewBundleIds is an array, JSON array, or string977 if (caps.additionalWebviewBundleIds) {978 caps.additionalWebviewBundleIds = this.helpers.parseCapsArray(caps.additionalWebviewBundleIds);979 }980 // finally, return true since the superclass check passed, as did this981 return true;982 }983 async installAUT () {984 if (this.isSafari()) {985 return;986 }987 await verifyApplicationPlatform(this.opts.app, {988 isSimulator: this.isSimulator(),989 isTvOS: this.isTvOS(),990 });991 if (this.isRealDevice()) {992 await installToRealDevice(this.opts.device, this.opts.app, this.opts.bundleId, {993 noReset: this.opts.noReset,994 timeout: this.opts.appPushTimeout,995 });996 } else {997 await installToSimulator(this.opts.device, this.opts.app, this.opts.bundleId, {998 noReset: this.opts.noReset,999 newSimulator: this.lifecycleData.createSim,1000 });1001 }1002 if (this.opts.otherApps) {1003 await this.installOtherApps(this.opts.otherApps);1004 }1005 if (util.hasValue(this.opts.iosInstallPause)) {1006 // https://github.com/appium/appium/issues/68891007 let pause = parseInt(this.opts.iosInstallPause, 10);1008 log.debug(`iosInstallPause set. Pausing ${pause} ms before continuing`);1009 await B.delay(pause);1010 }1011 }1012 async installOtherApps (otherApps) {1013 if (this.isRealDevice()) {1014 log.warn('Capability otherApps is only supported for Simulators');1015 return;1016 }1017 try {1018 otherApps = this.helpers.parseCapsArray(otherApps);1019 } catch (e) {1020 log.errorAndThrow(`Could not parse "otherApps" capability: ${e.message}`);1021 }1022 for (const otherApp of otherApps) {1023 await installToSimulator(this.opts.device, otherApp, undefined, {1024 noReset: this.opts.noReset,1025 newSimulator: this.lifecycleData.createSim,1026 });1027 }1028 }1029 /**1030 * Set reduceMotion as 'isEnabled' only when the capabilities has 'reduceMotion'1031 * The call is ignored for real devices.1032 * @param {?boolean} isEnabled Wether enable reduceMotion...
helpers.js
Source:helpers.js
1import _ from 'lodash';2import path from 'path';3import url from 'url';4import logger from './logger';5import _fs from 'fs';6import B from 'bluebird';7import { tempDir, fs, util, zip } from 'appium-support';8import request from 'request';9import asyncRequest from 'request-promise';10import LRU from 'lru-cache';11import AsyncLock from 'async-lock';12import sanitize from 'sanitize-filename';13const ZIP_EXTS = ['.zip', '.ipa'];14const ZIP_MIME_TYPES = [15 'application/zip',16 'application/x-zip-compressed',17 'multipart/x-zip',18];19const APPLICATIONS_CACHE = new LRU({20 max: 100,21});22const APPLICATIONS_CACHE_GUARD = new AsyncLock();23const SANITIZE_REPLACEMENT = '-';24const DEFAULT_BASENAME = 'appium-app';25async function retrieveHeaders (link) {26 try {27 const response = await asyncRequest({28 url: link,29 method: 'HEAD',30 resolveWithFullResponse: true,31 timeout: 5000,32 });33 return response.headers;34 } catch (e) {35 logger.debug(`Cannot send HEAD request to '${link}'. Original error: ${e.message}`);36 }37 return {};38}39function getCachedApplicationPath (link, currentModified) {40 if (!APPLICATIONS_CACHE.has(link) || !currentModified) {41 return null;42 }43 const {lastModified, fullPath} = APPLICATIONS_CACHE.get(link);44 if (lastModified && currentModified.getTime() <= lastModified.getTime()) {45 logger.debug(`Reusing already downloaded application at '${fullPath}'`);46 return fullPath;47 }48 logger.debug(`'Last-Modified' timestamp of '${link}' has been updated. ` +49 `An updated copy of the application is going to be downloaded.`);50 return null;51}52function verifyAppExtension (app, supportedAppExtensions) {53 if (supportedAppExtensions.includes(path.extname(app))) {54 return app;55 }56 throw new Error(`New app path '${app}' did not have extension(s) '${supportedAppExtensions}'`);57}58async function configureApp (app, supportedAppExtensions) {59 if (!_.isString(app)) {60 // immediately shortcircuit if not given an app61 return;62 }63 if (!_.isArray(supportedAppExtensions)) {64 supportedAppExtensions = [supportedAppExtensions];65 }66 let newApp = app;67 let shouldUnzipApp = false;68 let archiveHash = null;69 let currentModified = null;70 const {protocol, pathname} = url.parse(newApp);71 const isUrl = ['http:', 'https:'].includes(protocol);72 return await APPLICATIONS_CACHE_GUARD.acquire(app, async () => {73 if (isUrl) {74 // Use the app from remote URL75 logger.info(`Using downloadable app '${newApp}'`);76 const headers = await retrieveHeaders(newApp);77 if (headers['last-modified']) {78 logger.debug(`Last-Modified: ${headers['last-modified']}`);79 currentModified = new Date(headers['last-modified']);80 }81 const cachedPath = getCachedApplicationPath(app, currentModified);82 if (cachedPath) {83 if (await fs.exists(cachedPath)) {84 logger.info(`Reusing the previously downloaded application at '${cachedPath}'`);85 return verifyAppExtension(cachedPath, supportedAppExtensions);86 }87 logger.info(`The application at '${cachedPath}' does not exist anymore. Deleting it from the cache`);88 APPLICATIONS_CACHE.del(app);89 }90 let fileName = null;91 const basename = sanitize(path.basename(decodeURIComponent(pathname)), {92 replacement: SANITIZE_REPLACEMENT93 });94 const extname = path.extname(basename);95 // to determine if we need to unzip the app, we have a number of places96 // to look: content type, content disposition, or the file extension97 if (ZIP_EXTS.includes(extname)) {98 fileName = basename;99 shouldUnzipApp = true;100 }101 if (headers['content-type']) {102 logger.debug(`Content-Type: ${headers['content-type']}`);103 // the filetype may not be obvious for certain urls, so check the mime type too104 if (ZIP_MIME_TYPES.some(mimeType => new RegExp(`\\b${_.escapeRegExp(mimeType)}\\b`).test(headers['content-type']))) {105 if (!fileName) {106 fileName = `${DEFAULT_BASENAME}.zip`;107 }108 shouldUnzipApp = true;109 }110 }111 if (headers['content-disposition'] && /^attachment/i.test(headers['content-disposition'])) {112 logger.debug(`Content-Disposition: ${headers['content-disposition']}`);113 const match = /filename="([^"]+)/i.exec(headers['content-disposition']);114 if (match) {115 fileName = sanitize(match[1], {116 replacement: SANITIZE_REPLACEMENT117 });118 shouldUnzipApp = shouldUnzipApp || ZIP_EXTS.includes(path.extname(fileName));119 }120 }121 if (!fileName) {122 // assign the default file name and the extension if none has been detected123 const resultingName = basename124 ? basename.substring(0, basename.length - extname.length)125 : DEFAULT_BASENAME;126 let resultingExt = extname;127 if (!supportedAppExtensions.includes(resultingExt)) {128 logger.info(`The current file extension '${resultingExt}' is not supported. ` +129 `Defaulting to '${_.first(supportedAppExtensions)}'`);130 resultingExt = _.first(supportedAppExtensions);131 }132 fileName = `${resultingName}${resultingExt}`;133 }134 const targetPath = await tempDir.path({135 prefix: fileName,136 suffix: '',137 });138 newApp = await downloadApp(newApp, targetPath);139 } else if (await fs.exists(newApp)) {140 // Use the local app141 logger.info(`Using local app '${newApp}'`);142 shouldUnzipApp = ZIP_EXTS.includes(path.extname(newApp));143 } else {144 let errorMessage = `The application at '${newApp}' does not exist or is not accessible`;145 // protocol value for 'C:\\temp' is 'c:', so we check the length as well146 if (_.isString(protocol) && protocol.length > 2) {147 errorMessage = `The protocol '${protocol}' used in '${newApp}' is not supported. ` +148 `Only http: and https: protocols are supported`;149 }150 throw new Error(errorMessage);151 }152 if (shouldUnzipApp) {153 const archivePath = newApp;154 archiveHash = await fs.hash(archivePath);155 if (APPLICATIONS_CACHE.has(app) && archiveHash === APPLICATIONS_CACHE.get(app).hash) {156 const {fullPath} = APPLICATIONS_CACHE.get(app);157 if (await fs.exists(fullPath)) {158 if (archivePath !== app) {159 await fs.rimraf(archivePath);160 }161 logger.info(`Will reuse previously cached application at '${fullPath}'`);162 return verifyAppExtension(fullPath, supportedAppExtensions);163 }164 logger.info(`The application at '${fullPath}' does not exist anymore. Deleting it from the cache`);165 APPLICATIONS_CACHE.del(app);166 }167 const tmpRoot = await tempDir.openDir();168 try {169 newApp = await unzipApp(archivePath, tmpRoot, supportedAppExtensions);170 } finally {171 if (newApp !== archivePath && archivePath !== app) {172 await fs.rimraf(archivePath);173 }174 }175 logger.info(`Unzipped local app to '${newApp}'`);176 } else if (!path.isAbsolute(newApp)) {177 newApp = path.resolve(process.cwd(), newApp);178 logger.warn(`The current application path '${app}' is not absolute ` +179 `and has been rewritten to '${newApp}'. Consider using absolute paths rather than relative`);180 app = newApp;181 }182 verifyAppExtension(newApp, supportedAppExtensions);183 if (app !== newApp && (archiveHash || currentModified)) {184 APPLICATIONS_CACHE.set(app, {185 hash: archiveHash,186 lastModified: currentModified,187 fullPath: newApp,188 });189 }190 return newApp;191 });192}193async function downloadApp (app, targetPath) {194 const {href} = url.parse(app);195 const started = process.hrtime();196 try {197 // don't use request-promise here, we need streams198 await new B((resolve, reject) => {199 request(href)200 .on('error', reject) // handle real errors, like connection errors201 .on('response', (res) => {202 // handle responses that fail, like 404s203 if (res.statusCode >= 400) {204 return reject(new Error(`${res.statusCode} - ${res.statusMessage}`));205 }206 })207 .pipe(_fs.createWriteStream(targetPath))208 .on('close', resolve);209 });210 } catch (err) {211 throw new Error(`Problem downloading app from url ${href}: ${err.message}`);212 }213 const [seconds, ns] = process.hrtime(started);214 const secondsElapsed = seconds + ns / 1e09;215 const {size} = await fs.stat(targetPath);216 logger.debug(`'${href}' (${util.toReadableSizeString(size)}) ` +217 `has been downloaded to '${targetPath}' in ${secondsElapsed.toFixed(3)}s`);218 if (secondsElapsed >= 2) {219 const bytesPerSec = Math.floor(size / secondsElapsed);220 logger.debug(`Approximate download speed: ${util.toReadableSizeString(bytesPerSec)}/s`);221 }222 return targetPath;223}224async function walkDir (dir) {225 const result = [];226 for (const name of await fs.readdir(dir)) {227 const currentPath = path.join(dir, name);228 result.push(currentPath);229 if ((await fs.stat(currentPath)).isDirectory()) {230 result.push(...(await walkDir(currentPath)));231 }232 }233 return result;234}235async function unzipApp (zipPath, dstRoot, supportedAppExtensions) {236 await zip.assertValidZip(zipPath);237 if (!_.isArray(supportedAppExtensions)) {238 supportedAppExtensions = [supportedAppExtensions];239 }240 const tmpRoot = await tempDir.openDir();241 try {242 logger.debug(`Unzipping '${zipPath}'`);243 await zip.extractAllTo(zipPath, tmpRoot);244 const allExtractedItems = await walkDir(tmpRoot);245 logger.debug(`Extracted ${allExtractedItems.length} item(s) from '${zipPath}'`);246 const isSupportedAppItem = (relativePath) => supportedAppExtensions.includes(path.extname(relativePath))247 || _.some(supportedAppExtensions, (x) => relativePath.includes(`${x}${path.sep}`));248 const itemsToKeep = allExtractedItems249 .map((itemPath) => path.relative(tmpRoot, itemPath))250 .filter((relativePath) => isSupportedAppItem(relativePath))251 .map((relativePath) => path.resolve(tmpRoot, relativePath));252 const itemsToRemove = _.difference(allExtractedItems, itemsToKeep)253 // Avoid parent folders to be recursively removed254 .filter((itemToRemovePath) => !_.some(itemsToKeep, (itemToKeepPath) => itemToKeepPath.startsWith(itemToRemovePath)));255 await B.all(itemsToRemove, async (itemPath) => {256 if (await fs.exists(itemPath)) {257 await fs.rimraf(itemPath);258 }259 });260 const allBundleItems = (await walkDir(tmpRoot))261 .map((itemPath) => path.relative(tmpRoot, itemPath))262 .filter((relativePath) => isSupportedAppItem(relativePath))263 // Get the top level match264 .sort((a, b) => a.split(path.sep).length - b.split(path.sep).length);265 if (_.isEmpty(allBundleItems)) {266 throw new Error(`App zip unzipped OK, but we could not find ${supportedAppExtensions} bundle(s) ` +267 `in it. Make sure your archive contains ${supportedAppExtensions} package(s) ` +268 `and nothing else`);269 }270 const matchedBundle = _.first(allBundleItems);271 logger.debug(`Matched ${allBundleItems.length} item(s) in the extracted archive. ` +272 `Assuming '${matchedBundle}' is the correct bundle`);273 await fs.mv(path.resolve(tmpRoot, matchedBundle), path.resolve(dstRoot, matchedBundle), {274 mkdirp: true275 });276 return path.resolve(dstRoot, matchedBundle);277 } finally {278 await fs.rimraf(tmpRoot);279 }280}281function isPackageOrBundle (app) {282 return (/^([a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+)+$/).test(app);283}284function getCoordDefault (val) {285 // going the long way and checking for undefined and null since286 // we can't be assured `elId` is a string and not an int. Same287 // thing with destElement below.288 return util.hasValue(val) ? val : 0.5;289}290function getSwipeTouchDuration (waitGesture) {291 // the touch action api uses ms, we want seconds292 // 0.8 is the default time for the operation293 let duration = 0.8;294 if (typeof waitGesture.options.ms !== 'undefined' && waitGesture.options.ms) {295 duration = waitGesture.options.ms / 1000;296 if (duration === 0) {297 // set to a very low number, since they wanted it fast298 // but below 0.1 becomes 0 steps, which causes errors299 duration = 0.1;300 }301 }302 return duration;303}304/**305 * Finds all instances 'firstKey' and create a duplicate with the key 'secondKey',306 * Do the same thing in reverse. If we find 'secondKey', create a duplicate with the key 'firstKey'.307 *308 * This will cause keys to be overwritten if the object contains 'firstKey' and 'secondKey'.309 * @param {*} input Any type of input310 * @param {String} firstKey The first key to duplicate311 * @param {String} secondKey The second key to duplicate312 */313function duplicateKeys (input, firstKey, secondKey) {314 // If array provided, recursively call on all elements315 if (_.isArray(input)) {316 return input.map((item) => duplicateKeys(item, firstKey, secondKey));317 }318 // If object, create duplicates for keys and then recursively call on values319 if (_.isPlainObject(input)) {320 const resultObj = {};321 for (let [key, value] of _.toPairs(input)) {322 const recursivelyCalledValue = duplicateKeys(value, firstKey, secondKey);323 if (key === firstKey) {324 resultObj[secondKey] = recursivelyCalledValue;325 } else if (key === secondKey) {326 resultObj[firstKey] = recursivelyCalledValue;327 }328 resultObj[key] = recursivelyCalledValue;329 }330 return resultObj;331 }332 // Base case. Return primitives without doing anything.333 return input;334}335/**336 * Takes a desired capability and tries to JSON.parse it as an array,337 * and either returns the parsed array or a singleton array.338 *339 * @param {string|Array<String>} cap A desired capability340 */341function parseCapsArray (cap) {342 let parsedCaps;343 try {344 parsedCaps = JSON.parse(cap);345 if (_.isArray(parsedCaps)) {346 return parsedCaps;347 }348 } catch (ign) {349 logger.warn(`Failed to parse capability as JSON array`);350 }351 if (_.isString(cap)) {352 return [cap];353 }354 throw new Error(`must provide a string or JSON Array; received ${cap}`);355}356export {357 configureApp, isPackageOrBundle, getCoordDefault, getSwipeTouchDuration, duplicateKeys, parseCapsArray...
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 });...
helpers-specs.js
Source:helpers-specs.js
...90 });91});92describe('parseCapsArray', function () {93 it('should parse string into array', function () {94 parseCapsArray('/tmp/my/app.zip').should.eql(['/tmp/my/app.zip']);95 });96 it('should parse array as string into array', function () {97 parseCapsArray('["/tmp/my/app.zip"]').should.eql(['/tmp/my/app.zip']);98 parseCapsArray('["/tmp/my/app.zip","/tmp/my/app2.zip"]').should.eql([99 '/tmp/my/app.zip',100 '/tmp/my/app2.zip'101 ]);102 });103 it('should return an array without change', function () {104 parseCapsArray(['a', 'b']).should.eql(['a', 'b']);105 });...
Using AI Code Generation
1const { parseCapsArray } = require('appium-base-driver');2const caps = parseCapsArray(['--platformName', 'iOS', '--platformVersion', '12.0', '--deviceName', 'iPhone X']);3console.log(caps);4const { parseCapsArray } = require('appium-base-driver');5const caps = parseCapsArray(['--platformName', 'iOS', '--platformVersion', '12.0', '--deviceName', 'iPhone X']);6console.log(caps);7const { parseCapsArray } = require('appium-base-driver');8const caps = parseCapsArray(['--platformName', 'iOS', '--platformVersion', '12.0', '--deviceName', 'iPhone X']);9console.log(caps);10const { parseCapsArray } = require('appium-base-driver');11const caps = parseCapsArray(['--platformName', 'iOS', '--platformVersion', '12.0', '--deviceName', 'iPhone X']);12console.log(caps);13const { parseCapsArray } = require('appium-base-driver');14const caps = parseCapsArray(['--platformName', 'iOS', '--platformVersion', '12.0', '--deviceName', 'iPhone X']);15console.log(caps);16const { parseCapsArray } = require('appium-base-driver');17const caps = parseCapsArray(['--platformName', 'iOS', '--platformVersion', '12.0', '--deviceName', 'iPhone X']);18console.log(caps);19const { parseCapsArray } = require('appium-base-driver');20const caps = parseCapsArray(['--platformName', 'iOS', '--platformVersion', '12.0', '--deviceName', 'iPhone X']);21console.log(caps);22const { parseCapsArray } = require('appium-base-driver');
Using AI Code Generation
1var BaseDriver = require('appium-base-driver');2var capsArray = BaseDriver.parseCapsArray([{"deviceName":"device1","platformName":"android"},{"deviceName":"device2","platformName":"android"}]);3console.log(capsArray);4var AndroidDriver = require('appium-android-driver');5var capsArray = AndroidDriver.parseCapsArray([{"deviceName":"device1","platformName":"android"},{"deviceName":"device2","platformName":"android"}]);6console.log(capsArray);7[ { deviceName: 'device1', platformName: 'android' },8 { deviceName: 'device2', platformName: 'android' } ]9[ { deviceName: 'device1', platformName: 'android' },10 { deviceName: 'device2', platformName: 'android' } ]
Using AI Code Generation
1const { parseCapsArray } = require('appium-base-driver');2const caps = parseCapsArray(['--platformName', 'iOS']);3console.log(caps);4const { parseCapsArray } = require('appium-base-driver');5const caps = parseCapsArray(['--platformName', 'iOS', '--deviceName', 'iPhone 6']);6console.log(caps);7const { parseCapsArray } = require('appium-base-driver');8const caps = parseCapsArray(['--platformName', 'iOS', '--deviceName', 'iPhone 6', '--app', '/Users/username/Desktop/appium/appium-examples/apps/TestApp.app.zip']);9console.log(caps);10const { parseCapsArray } = require('appium-base-driver');11const caps = parseCapsArray(['--platformName', 'iOS', '--deviceName', 'iPhone 6', '--app', '/Users/username/Desktop/appium/appium-examples/apps/TestApp.app.zip', '--appium-version', '1.6.6']);12console.log(caps);13const { parseCapsArray } = require('appium-base-driver');14const caps = parseCapsArray(['--platformName', 'iOS', '--deviceName', 'iPhone 6', '--app', '/Users/username/Desktop/appium/appium-examples/apps/TestApp.app.zip', '--appium-version', '1.6.6', '--automation-name', 'XCUITest']);15console.log(caps);
Using AI Code Generation
1var BaseDriver = require('appium-base-driver').BaseDriver;2var bDriver = new BaseDriver();3var caps = bDriver.parseCapsArray(['platformName=Android', 'deviceName=Android Emulator', 'app=/Users/username/Downloads/test.apk']);4console.log(caps);5{ platformName: 'Android',6 app: '/Users/username/Downloads/test.apk' }
Using AI Code Generation
1var BaseDriver = require('appium-base-driver');2var capsArray = BaseDriver.parseCapsArray(process.argv);3console.log(capsArray);4[ { platformName: 'Android',5 app: '/Users/username/Downloads/test.apk' } ]6parseCapsArray() method of Appium Base Driver7parseCapsArray() method of Appium Base Driver is used to parse capabilities array. It takes an array of capabilities and returns an array of objects. It is used to parse the capabilities array. It is used to parse the c
Using AI Code Generation
1const AppiumBaseDriver = require('appium-base-driver');2let caps = [‘--no-reset’, ‘--session-override’, ‘--command-timeout=600’];3let parsedCaps = AppiumBaseDriver.parseCapsArray(caps);4console.log(parsedCaps);5{ noReset: true, sessionOverride: true, commandTimeout: 600 }6caps {Array.<String>} - an array of capabilities, e.g., [‘--no-reset’, ‘--session-override’, ‘--command-timeout=600’]7{Object} - an object of capabilities, e.g., {noReset: true, sessionOverride: true, commandTimeout: 600}8let caps = [‘--no-reset’, ‘--session-override’, ‘--command-timeout=600’];9let parsedCaps = AppiumBaseDriver.parseCapsArray(caps);10console.log(parsedCaps);11{ noReset: true, sessionOverride: true, commandTimeout: 600 }
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!!