Best JavaScript code snippet using appium-xcuitest-driver
ios-controller.js
Source:ios-controller.js
...1400 var pageIdKey = parseInt(idx, 10);1401 var next = function () {1402 this.processingRemoteCmd = true;1403 if (this.args.udid === null) {1404 this.remote.selectPage(pageIdKey, function () {1405 this.curContext = idx;1406 cb(null, {1407 status: status.codes.Success.code1408 , value: ''1409 });1410 this.processingRemoteCmd = false;1411 }.bind(this), skipReadyCheck);1412 } else {1413 if (name === this.curContext) {1414 logger.debug("Remote debugger is already connected to window [" + name + "]");1415 cb(null, {1416 status: status.codes.Success.code1417 , value: name1418 });1419 } else {1420 this.remote.disconnect(function () {1421 this.curContext = idx;1422 this.remote.connect(idx, function () {1423 cb(null, {1424 status: status.codes.Success.code1425 , value: name1426 });1427 });1428 }.bind(this));1429 }1430 }1431 }.bind(this);1432 next();1433 } else {1434 cb(null, {1435 status: status.codes.NoSuchContext.code1436 , value: "Context '" + name + "' does not exist"1437 });1438 }1439 }.bind(this);1440 // only get contexts if they haven't already been gotten1441 if (typeof this.contexts === 'undefined') {1442 this.getContexts(function () {1443 pickContext();1444 }.bind(this));1445 } else {1446 pickContext();1447 }1448 }1449};1450iOSController.getWindowHandle = function (cb) {1451 if (this.isWebContext()) {1452 var windowHandle = this.curContext;1453 var response = {1454 status: status.codes.Success.code1455 , value: windowHandle1456 };1457 cb(null, response);1458 } else {1459 cb(new NotImplementedError(), null);1460 }1461};1462iOSController.massagePage = function (page) {1463 page.id = page.id.toString();1464 return page;1465};1466iOSController.getWindowHandles = function (cb) {1467 if (!this.isWebContext()) {1468 return cb(new NotImplementedError(), null);1469 }1470 this.listWebFrames(function (err, pageArray) {1471 if (err) {1472 return cb(err);1473 }1474 this.windowHandleCache = _.map(pageArray, this.massagePage);1475 var idArray = _.pluck(this.windowHandleCache, 'id');1476 // since we use this.contexts to manage selecting debugger pages, make1477 // sure it gets populated even if someone did not use the1478 // getContexts method1479 if (!this.contexts) {1480 this.contexts = idArray;1481 }1482 cb(null, {1483 status: status.codes.Success.code1484 , value: idArray1485 });1486 }.bind(this));1487};1488iOSController.setWindow = function (name, cb, skipReadyCheck) {1489 if (!this.isWebContext()) {1490 return cb(new NotImplementedError(), null);1491 }1492 if (_.contains(_.pluck(this.windowHandleCache, 'id'), name)) {1493 var pageIdKey = parseInt(name, 10);1494 var next = function () {1495 this.processingRemoteCmd = true;1496 if (this.args.udid === null) {1497 this.remote.selectPage(pageIdKey, function () {1498 this.curContext = pageIdKey.toString();1499 this.curWindowHandle = pageIdKey.toString();1500 cb(null, {1501 status: status.codes.Success.code1502 , value: ''1503 });1504 this.processingRemoteCmd = false;1505 }.bind(this), skipReadyCheck);1506 } else {1507 if (name === this.curWindowHandle) {1508 logger.debug("Remote debugger is already connected to window [" + name + "]");1509 cb(null, {1510 status: status.codes.Success.code1511 , value: name...
context.js
Source:context.js
...37 throw new errors.NoSuchContextError();38 }39 let pageIdKey = parseInt(idx, 10);40 if (!this.isRealDevice()) {41 await this.remote.selectPage(pageIdKey, skipReadyCheck);42 this.curContext = idx;43 } else {44 if (this.remote) {45 await this.remote.disconnect();46 }47 this.curContext = idx;48 await this.remote.connect(idx);49 }50 }51 // attempt to start performance logging, if requested52 if (this.perfLogEnabled && this.remote) {53 logger.debug(`Starting performance log on '${this.curContext}'`);54 this.logs.performance = new IOSPerformanceLog(this.remote);55 this.logs.performance.startCapture();56 }57};58commands.getWindowHandle = async function () {59 if (!this.isWebContext()) {60 throw new errors.NotImplementedError();61 }62 return this.curContext;63};64commands.getWindowHandles = async function () {65 if (!this.isWebContext()) {66 throw new errors.NotImplementedError();67 }68 let pageArray = await this.listWebFrames();69 this.windowHandleCache = _.map(pageArray, this.massagePage);70 let idArray = _.pluck(this.windowHandleCache, 'id');71 // since we use this.contexts to manage selecting debugger pages, make72 // sure it gets populated even if someone did not use the73 // getContexts method74 if (!this.contexts) {75 this.contexts = idArray;76 }77 return idArray;78};79commands.setWindow = async function (name, skipReadyCheck) {80 if (!this.isWebContext()) {81 throw new errors.NotImplementedError();82 }83 if (!_.contains(_.pluck(this.windowHandleCache, 'id'), name)) {84 throw new errors.NoSuchWindowError();85 }86 let pageIdKey = parseInt(name, 10);87 if (!this.isRealDevice()) {88 await this.remote.selectPage(pageIdKey, skipReadyCheck);89 this.curContext = this.curWindowHandle = name;90 } else {91 if (name === this.curWindowHandle) {92 logger.debug(`Remote debugger is already connected to window '${name}'`);93 } else if (!_.contains(_.pluck(this.windowHandleCache, 'id'), name)) {94 throw new errors.NoSuchWindowError();95 } else {96 await this.remote.disconnect();97 this.curContext = this.curWindowHandle = name;98 await this.remote.connect(name);99 }100 }101};102helpers.webContextIndex = function () {103 return this.curContext.replace(WEBVIEW_BASE, '') - 1;104};105extensions.getContextsAndViews = async function () {106 logger.debug('Retrieving contexts and views');107 let webviews = await this.listWebFrames();108 let ctxs = [];109 this.contexts = [];110 for (let view of webviews) {111 ctxs.push({id: `${WEBVIEW_BASE}${view.id}`, view});112 this.contexts.push(view.id.toString());113 }114 return ctxs;115};116extensions.listWebFrames = async function () {117 if (!this.opts.bundleId) {118 logger.errorAndThrow('Cannot enter web frame without a bundle ID');119 }120 let pageArray;121 if (this.remote !== null && this.opts.bundleId !== null) {122 if (this.isRealDevice()) {123 pageArray = await this.remote.pageArrayFromJson();124 } else {125 pageArray = await this.remote.selectApp(this.opts.webviewConnectRetries);126 }127 } else {128 if (this.isRealDevice()) {129 this.remote = new WebKitRemoteDebugger({port: this.opts.webkitDebugProxyPort});130 return this.remote.pageArrayFromJson();131 }132 this.remote = new RemoteDebugger({133 bundleId: this.opts.bundleId,134 useNewSafari: this.useNewSafari(),135 pageLoadMs: this.pageLoadMs,136 platformVersion: this.opts.platformVersion137 });138 logger.info('attempting to connect to remote debugger');139 let appInfo = await this.remote.connect();140 logger.info('connected to remote debugger');141 if (!appInfo) {142 logger.debug('Unable to connect to the remote debugger.');143 return [];144 }145 logger.info('getting page array by calling "selectApp()"');146 pageArray = await this.remote.selectApp(this.opts.webviewConnectRetries);147 logger.info(`we got page array ${pageArray.length}`);148 this.remote.on(RemoteDebugger.EVENT_PAGE_CHANGE, this.onPageChange.bind(this));149 // TODO: do we need to close alerts here?150 // let tryClosingAlert = async () => {151 // let didDismiss = await this.closeAlertBeforeTest();152 // if (!didDismiss) {153 // throw new Error('Close alert failed. Retry.');154 // }155 // };156 // try {157 // await retryInterval(3, 4000, tryClosingAlert);158 // } catch (err) {159 // // if the loop to close alerts failed to dismiss, ignore,160 // // otherwise log and throw the error161 // if (err.message !== 'Close alert failed. Retry.') {162 // logger.errorAndThrow(err);163 // }164 // }165 }166 if (pageArray.length === 0) {167 // we have no web frames, but continue anyway168 logger.debug('No web frames found.');169 }170 return pageArray;171};172extensions.onPageChange = async function (pageArray) {173 logger.debug(`Remote debugger notified us of a new page listing: ${JSON.stringify(pageArray)}`);174 if (this.selectingNewPage) {175 logger.debug('We are in the middle of selecting a page, ignoring');176 return;177 }178 let newIds = [];179 let newPages = [];180 let keyId = null;181 for (let page of pageArray) {182 let id = page.id.toString();183 newIds.push(id);184 if (page.isKey) {185 keyId = id;186 }187 if (!_.contains(this.contexts, id)) {188 newPages.push(id);189 this.contexts.push(id);190 }191 }192 let newPage = null;193 if (this.curContext === null) {194 logger.debug('We do not appear to have window set yet, ignoring');195 } else if (newPages.length) {196 logger.debug(`We have new pages, going to select page '${newPages[0]}'`);197 newPage = newPages[0];198 } else if (!_.contains(newIds, this.curContext.toString())) {199 logger.debug('New page listing from remote debugger does not contain ' +200 'current window; assuming it is closed');201 if (keyId !== null) {202 logger.debug(`Debugger already selected page '${keyId}', ` +203 `confirming that choice.`);204 } else {205 logger.error('Do not have our current window anymore, and there ' +206 'are not any more to load! Doing nothing...');207 return;208 }209 this.curContext = keyId;210 newPage = keyId;211 } else {212 // If a window navigates to an anchor it doesn't always fire a page213 // callback event. Let's check if we wound up in such a situation.214 let needsPageLoad = (() => {215 let item = (arr) => {216 return _.filter(arr, function (obj) {217 return obj.id === this.curContext;218 }, this)[0];219 };220 return !_.isEqual(item(this.contexts), item(pageArray));221 })();222 if (needsPageLoad) {223 await this.remote.pageLoad();224 }225 logger.debug('New page listing is same as old, doing nothing');226 }227 if (!_.isNull(newPage)) {228 this.selectingNewPage = true;229 await this.remote.selectPage(parseInt(newPage, 10));230 this.selectingNewPage = false;231 this.curContext = newPage;232 }233 this.windowHandleCache = _.map(pageArray, this.massagePage);234};235extensions.getLatestWebviewContextForTitle = async function (titleRegex) {236 let contexts = await this.getContextsAndViews();237 let matchingCtx;238 for (let ctx of contexts) {239 if (ctx.view && (ctx.view.title || '').match(titleRegex)) {240 if (ctx.view.url !== 'about:blank') {241 matchingCtx = ctx;242 } else {243 // in the cases of Xcode < 5 (i.e., iOS SDK Version less than 7)...
ios-hybrid.js
Source:ios-hybrid.js
...131 logger.debug("New page listing is same as old, doing nothing");132 }133 if (newPage !== null) {134 this.selectingNewPage = true;135 this.remote.selectPage(parseInt(newPage, 10), function () {136 this.selectingNewPage = false;137 this.curContext = newPage;138 if (this.onPageChangeCb !== null) {139 this.onPageChangeCb();140 this.onPageChangeCb = null;141 }142 }.bind(this));143 } else if (this.onPageChangeCb !== null) {144 this.onPageChangeCb();145 this.onPageChangeCb = null;146 }147 this.windowHandleCache = _.map(pageArray, this.massagePage);148};149iOSHybrid.getAtomsElement = deviceCommon.getAtomsElement;...
driver.js
Source:driver.js
...42 if (!pages.length) {43 throw new Error('Could not find Safari or an app with webviews running');44 }45 log.info('Selecting first page');46 await this.remote.selectPage(pages[0].id);47 log.info('Safari session ready to receive commands');48 }49 async deleteSession () {50 if (this.remote) {51 await this.remote.disconnect();52 }53 await super.deleteSession();54 }55 // TODO replace this stub56 isWebContext () {57 return true;58 }59 // TODO replace this stub60 isRealDevice () {...
Using AI Code Generation
1const { remote } = require('webdriverio');2(async () => {3 const browser = await remote({4 capabilities: {5 }6 })7 await browser.pause(2000)8 await browser.selectPage(1)9 await browser.pause(2000)10 await browser.selectPage(0)11 await browser.pause(2000)12 await browser.deleteSession()13})().catch(async (e) => {14 console.error(e);15 await browser.deleteSession()16});17from appium import webdriver18from time import sleep19caps = {}20driver.implicitly_wait(10)21sleep(2)22driver.selectPage(1)23sleep(2)24driver.selectPage(0)25sleep(2)26driver.quit()27* Appium version (or git revision) that exhibits the issue: 1.15.128* Last Appium version that did not exhibit the issue (if applicable): NA29* Node.js version (unless using Appium.app|exe): v12.13.0
Using AI Code Generation
1const { remote } = require('webdriverio');2(async () => {3 const browser = await remote({4 capabilities: {5 }6 });7 await browser.selectPage(1);8 await browser.selectPage('main');9 await browser.selectPage();10 await browser.deleteSession();11})();12const { remote } = require('webdriverio');13(async () => {14 const browser = await remote({15 capabilities: {16 }17 });18 await browser.selectPage(1);19 await browser.selectPage('main');20 await browser.selectPage();21 await browser.deleteSession();22})();23const { remote } = require('webdriverio');24(async () => {25 const browser = await remote({26 capabilities: {27 }28 });29 await browser.selectPage(1);30 await browser.selectPage('main');31 await browser.selectPage();32 await browser.deleteSession();33})();34const { remote } = require('webdriverio');35(async () => {36 const browser = await remote({37 capabilities: {
Using AI Code Generation
1const { remote } = require('webdriverio')2const assert = require('assert')3async function example () {4 const browser = await remote({5 capabilities: {6 }7 })8 const contexts = await browser.getContexts()9 await browser.selectContext(contexts[1])10 const el = await browser.$('h1')11 const text = await el.getText()12 assert.strictEqual(text, 'My Page')13 await browser.selectContext(contexts[0])14 const el = await browser.$('XCUIElementTypeStaticText')15 const text = await el.getText()16 assert.strictEqual(text, 'My Native App')17 await browser.deleteSession()18}19example()20const { remote } = require('webdriverio')21const assert = require('assert')22async function example () {23 const browser = await remote({24 capabilities: {25 }26 })27 const contexts = await browser.getContexts()28 await browser.switchToFrame(contexts[1])29 const el = await browser.$('h1')30 const text = await el.getText()31 assert.strictEqual(text, 'My Page')32 await browser.switchToFrame(contexts[0])33 const el = await browser.$('XCUIElementTypeStaticText')34 const text = await el.getText()35 assert.strictEqual(text, 'My Native App')36 await browser.deleteSession()37}38example()
Using AI Code Generation
1var webdriverio = require('webdriverio');2var assert = require('assert');3var opts = {4 desiredCapabilities: {5 }6};7var client = webdriverio.remote(opts);8 .init()9 .then(function () {10 return client.selectPage('WEBVIEW');11 })12 .then(function () {13 return client.selectPage('NATIVE_APP');14 })15 .end();
Using AI Code Generation
1const { remote } = require('webdriverio');2const client = remote({3 capabilities: {4 }5});6client.init();7client.selectPage(2);8client.selectPage(1);9client.selectPage(0);10client.end();
Using AI Code Generation
1const wdio = require('webdriverio');2const opts = {3 capabilities: {4 }5};6async function main () {7 const client = await wdio.remote(opts);8 await client.selectPage(1);9 await client.selectPage(2);10 await client.selectPage(0);11 await client.selectPage(1);12 await client.deleteSession();13}14main();15const wdio = require('webdriverio');16const opts = {17 capabilities: {18 }19};20async function main () {21 const client = await wdio.remote(opts);22 await client.selectPage(1);23 await client.selectPage(2);24 await client.selectPage(0);25 await client.selectPage(1);26 await client.deleteSession();27}28main();29const wdio = require('webdriverio');30const opts = {31 capabilities: {32 }33};34async function main () {35 const client = await wdio.remote(opts);36 await client.selectPage(1);37 await client.selectPage(2);38 await client.selectPage(0);39 await client.selectPage(1);40 await client.deleteSession();41}42main();
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!!