Best JavaScript code snippet using appium-xcuitest-driver
ApiDriver.js
Source:ApiDriver.js
1/**2 * Created by AlexanderC on 2/3/16.3 */4'use strict';5import {AbstractDriver} from './AbstractDriver';6import request from 'fetchy-request';7import util from '../../../Helpers/util';8import {RegistryAutoDiscovery} from './Helpers/Api/RegistryAutoDiscovery';9import path from 'path';10export class ApiDriver extends AbstractDriver {11 /**12 * @param {RegistryConfig|*} registryConfig13 */14 constructor(registryConfig) {15 super();16 this._authorizer = null;17 this._registryConfig = registryConfig;18 this._endpoints = registryConfig.extract();19 }20 /**21 * @param {String} baseHost22 * @param {Function} cb23 * @param {Boolean} cached24 */25 static autoDiscover(baseHost, cb, cached = false) {26 (new RegistryAutoDiscovery(baseHost))[cached ? 'discoverCached' : 'discover']((error, registryConfig) => {27 if (error) {28 cb(error, null);29 return;30 }31 try {32 cb(null, new ApiDriver(registryConfig));33 } catch (exception) {34 cb(exception, null);35 }36 });37 }38 /**39 * @returns {Authorizer|null}40 */41 get authorizer() {42 return this._authorizer;43 }44 /**45 * @param {Authorizer|null} authorizer46 */47 set authorizer(authorizer) {48 this._authorizer = authorizer;49 }50 /**51 * @returns {Object}52 */53 get endpoints() {54 return this._endpoints;55 }56 /**57 * @returns {RegistryConfig|*}58 */59 get registryConfig() {60 return this._registryConfig;61 }62 /**63 * @param {String} objPath64 * @param {Function} cb65 */66 hasObj(objPath, cb) {67 this._request('hasObj', objPath, (error, data) => {68 let resultError = error || data.error;69 cb(resultError, resultError ? null : data.data);70 });71 }72 /**73 * @param {String} objPath74 * @param {Function} cb75 */76 readObj(objPath, cb) {77 this._request('readObj', objPath, (error, data) => {78 let resultError = error || data.error;79 cb(resultError, resultError ? null : data.data);80 });81 }82 /**83 * @param {String} objPath84 * @param {String|*} data85 * @param {Function} cb86 */87 putObj(objPath, data, cb) {88 this._request('putObj', objPath, (error, data) => {89 cb(error || data.error);90 }, data);91 }92 /**93 * @param {String} objPath94 * @param {Function} cb95 */96 deleteObj(objPath, cb) {97 this._request('deleteObj', objPath, (error, data) => {98 cb(error || data.error);99 });100 }101 /**102 * @param {String} objPath103 * @param {Function} cb104 */105 lockObj(objPath, cb) {106 this.putObj(ApiDriver._lockObjPath(objPath), '', cb);107 }108 /**109 * @param {String} objPath110 * @param {Function} cb111 */112 isObjLocked(objPath, cb) {113 this.hasObj(ApiDriver._lockObjPath(objPath), cb);114 }115 /**116 * @param {String} objPath117 * @param {Function} cb118 */119 releaseObjLock(objPath, cb) {120 this.deleteObj(ApiDriver._lockObjPath(objPath), cb);121 }122 /**123 * @param {String} objPath124 * @returns {String}125 * @private126 */127 static _lockObjPath(objPath) {128 return `${path.dirname(objPath)}/.${path.basename(objPath)}.lock`;129 }130 /**131 * @param {String} endpointName132 * @param {String} objPath133 * @param {Function} cb134 * @param {Object|null} data135 * @private136 */137 _request(endpointName, objPath, cb, data = null) {138 let payload = {objPath,};139 if (data !== null) {140 payload.data = ApiDriver._encodeResponseData(endpointName, data);141 }142 let requestData = {143 uri: this._endpoints[endpointName],144 method: 'POST',145 retry: ApiDriver.RETRY_COUNT,146 displayName: `POST:${endpointName}`,147 headers: {'Content-Type': 'application/json',},148 body: JSON.stringify(payload),149 };150 if (this._authorizer) {151 this._authorizer.injectIntoRequest(requestData);152 }153 request(requestData)154 .then((response) => {155 if (!response.ok) {156 cb(response._error || new Error(response.statusText), null);157 return;158 }159 response160 .text()161 .then((plainData) => {162 let data = null;163 let parsedData = null;164 try {165 data = JSON.parse(plainData);166 } catch (error) {167 data = ApiDriver._decodeData(plainData);168 }169 if (data.errorMessage) {170 cb(ApiDriver._extractError(data.errorMessage), null);171 return;172 }173 parsedData = util.isObject(data) ? data : {};174 // mimic callback args175 parsedData.data = ApiDriver._decodeResponseData(endpointName, parsedData.data || null);176 parsedData.error = parsedData.error || null;177 if (parsedData.error) {178 parsedData.error = ApiDriver._extractError(parsedData.error);179 }180 cb(null, parsedData);181 })182 .catch((error) => {183 cb(error, null);184 });185 }).catch((error) => {186 cb(error, null);187 });188 }189 /**190 * @param {String|Object} data191 * @returns {Object}192 * @private193 */194 static _decodeData(data) {195 if (util.isObject(data)) {196 return data;197 }198 try {199 return JSON.parse(data);200 } catch (e) {201 console.debug('Unable to parse: ', e);202 }203 return {};204 }205 /**206 * @param {String} rawErrorData207 * @returns {Error}208 * @private209 */210 static _extractError(rawErrorData) {211 if (util.isObject(rawErrorData)) {212 return new Error(213 rawErrorData.errorMessage.toString() ||214 `An unknown error occurred (${JSON.stringify(rawErrorData)})`215 );216 }217 let errorMsg = rawErrorData;218 try {219 let errorObj = JSON.parse(rawErrorData);220 errorMsg = errorObj.errorMessage || `An unknown error occurred (${rawErrorData})`;221 } catch (error) {222 console.debug('Unable to parse: ', error);223 }224 return new Error(errorMsg);225 }226 /**227 * @param {String} endpointName228 * @param {String|*} data229 * @returns {String|*}230 */231 static _encodeResponseData(endpointName, data) {232 if (['putObj', 'readObj'].indexOf(endpointName) === -1) {233 return data;234 }235 return data ? (new Buffer(data.toString())).toString('base64') : data;236 }237 /**238 * @param {String} endpointName239 * @param {String|*} rawData240 * @returns {String|*}241 */242 static _decodeResponseData(endpointName, rawData) {243 if (['putObj', 'readObj'].indexOf(endpointName) === -1) {244 return rawData;245 }246 return rawData ? (new Buffer(rawData.toString(), 'base64')).toString('ascii') : rawData;247 }248 /**249 * @returns {Number}250 */251 static get RETRY_COUNT() {252 return 3;253 }...
index.js
Source:index.js
...31 const key = lockerFactory.hash(resourceId);32 const retry = dget(options, 'retry', false);33 const retryInterval = dget(options, 'retryInterval', DEFAULT_RETRY_INTERVAL);34 let maxRetryAttempts = dget(options, 'maxRetryAttempts', DEFAULT_RETRY_ATTEMPTS);35 return driver.lock(key, options)36 .then(numberOfLocks => handleLockingResult(numberOfLocks));37 function handleLockingResult(numberOfLocks) {38 if (numberOfLocks === 1) {39 return buildLock(resourceId, key);40 }41 if (retry && --maxRetryAttempts >= 0) {42 return retryLockingAfterTimeout();43 }44 throw new ResourceLockedError(resourceId, numberOfLocks);45 }46 function retryLockingAfterTimeout() {47 return promiseTimeout(retryInterval)48 .then(() => driver.lock(key, options))49 .then(numberOfLocks => handleLockingResult(numberOfLocks));50 }51 function promiseTimeout(duration) {52 return new Promise(resolve => setTimeout(resolve, duration));53 }54 function dget(obj, key, def) {55 if (!obj || 'undefined' === typeof obj[key]) {56 return def;57 }58 const val = obj[key];59 delete obj[key];60 return val;61 }62 }...
lock-specs.js
Source:lock-specs.js
1"use strict";2var setup = require("../../common/setup-base")3 , desired = require("./desired")4 , Asserter = require('wd').Asserter5 , chai = require('chai');6describe("apidemos - lock", function () {7 var driver;8 setup(this, desired).then(function (d) { driver = d; });9 var isLockedAsserter = function (opts) {10 return new Asserter(11 function (driver) {12 return driver13 .isLocked()14 .then(function (isLocked) {15 isLocked.should.equal(opts.expected);16 return isLocked;17 })18 .catch(function (err) {19 err.retriable = err instanceof chai.AssertionError;20 throw err;21 });22 }23 );24 };25 it('should lock the screen', function (done) {26 driver27 .isLocked()28 .should.not.eventually.be.ok29 .lockDevice(3)30 .waitFor(isLockedAsserter({expected: true}), 5000, 500)31 .should.eventually.be.ok32 .nodeify(done);33 });34 // TODO: flaky test35 it('should unlock the screen @skip-ci', function (done) {36 driver37 .lockDevice(3)38 .waitFor(isLockedAsserter({expected: true}), 5000, 500)39 .should.eventually.be.ok40 .unlockDevice()41 .sleep(1000)42 .waitFor(isLockedAsserter({expected: false}), 10000, 1000)43 .should.not.eventually.be.ok44 .nodeify(done);45 });...
device-specs.js
Source:device-specs.js
1"use strict";2var env = require('../../../helpers/env'),3 setup = require("../../common/setup-base"),4 desired = require('./desired');5describe('uicatalog - device @skip-ios7up', function () {6 describe('lock device', function () {7 var driver;8 setup(this, desired).then(function (d) { driver = d; });9 var allowance = env.IOS7 ? 5 : 2;10 it("should lock the device for 4 of seconds (+/- " + allowance + " secs)", function (done) {11 var before = new Date().getTime() / 1000;12 driver13 .lockDevice(4)14 .then(function () {15 var now = (new Date().getTime() / 1000);16 (now - before).should.be.above(4);17 (now - before).should.be.below(4 + allowance + 1);18 }).nodeify(done);19 });20 });21 describe('background app', function () {22 var driver;23 setup(this, desired).then(function (d) { driver = d; });24 it("should background the app for 4 of seconds (+/- 6 secs)", function (done) {25 var before = new Date().getTime() / 1000;26 driver27 .backgroundApp(4)28 .then(function () {29 ((new Date().getTime() / 1000) - before).should.be.below(11);30 }).nodeify(done);31 });32 });...
lock-device-specs.js
Source:lock-device-specs.js
...5 let driver = session.driver;6 let allowance = 10;7 it(`should lock the device for 4 seconds (+/- ${allowance} secs)`, async function () {8 let before = new Date().getTime() / 1000;9 await driver.lock(4);10 let now = (new Date().getTime() / 1000);11 (now - before).should.be.above(4);12 (now - before).should.be.below(4 + allowance + 1);13 });14 it(`should default to 0 lock the device for +/- ${allowance} secs`, async function () {15 let before = new Date().getTime() / 1000;16 await driver.lock(0);17 let now = (new Date().getTime() / 1000);18 (now - before).should.be.above(0);19 (now - before).should.be.below(allowance + 1);20 });...
steps.js
Source:steps.js
...4Given(/^I open the demo app$/, async () => {5 await console.log('Mobile app is open');6});7When(/^I lock device$/, async () => {8 await driver.lock();9});10When(/^I unlock device$/, async () => {11 await driver.unlock();12});13When(/^I navigate to login tab$/, async () => {14 await LandingPage.btnLogin_tap();15});16When(17 /^I initiate login with ([^"]*)? and ([^"]*)?$/,18 async (email, password) => {19 await LoginPage.txtEmail_setText(email);20 await LoginPage.txtPassword_setText(password);21 await LoginPage.btnLogin_tap();22 },...
variables_6c.js
Source:variables_6c.js
1var searchData=2[3 ['location',['location',['../structprinter__driver.html#a6a0d5603410d5eda93c0ff341966cce1',1,'printer_driver']]],4 ['lock',['lock',['../structprint__job__list.html#a0abaf4b5d42c4e5d19190035fade3599',1,'print_job_list']]],5 ['logfile',['logfile',['../main_8c.html#ab25a3625a8efbaa3d81ef27bbb51c9c5',1,'main.c']]],6 ['logname',['logname',['../main_8c.html#a9fedf8eb982ca1b1aa71c127d299620d',1,'main.c']]]...
all_6c.js
Source:all_6c.js
1var searchData=2[3 ['location',['location',['../structprinter__driver.html#a6a0d5603410d5eda93c0ff341966cce1',1,'printer_driver']]],4 ['lock',['lock',['../structprint__job__list.html#a0abaf4b5d42c4e5d19190035fade3599',1,'print_job_list']]],5 ['logfile',['logfile',['../main_8c.html#ab25a3625a8efbaa3d81ef27bbb51c9c5',1,'main.c']]],6 ['logname',['logname',['../main_8c.html#a9fedf8eb982ca1b1aa71c127d299620d',1,'main.c']]]...
Using AI Code Generation
1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5chai.should();6const username = process.env.SAUCE_USERNAME;7const accessKey = process.env.SAUCE_ACCESS_KEY;8const driver = wd.promiseChainRemote('ondemand.saucelabs.com', 80, username, accessKey);9describe('Test', function () {10 this.timeout(300000);11 it('should lock the device', async function () {12 await driver.init({13 });14 await driver.lock(10);15 await driver.unlock();16 await driver.quit();17 });18});19at XCUITestDriver.executeCommand (/Users/isaacmurchie/Downloads/isaacmurchie-macbook-pro-2-2019-04-16-13-58-53/node_modules/appium/node_modules/appium-xcuitest-driver/lib/commands/execute.js:18:11)20at AppiumDriver.executeCommand (/Users/isaacmurchie/Downloads/isaacmurchie-macbook-pro-2-2019-04-16-13-58-53/node_modules/appium/lib/appium.js:360:36)21at commandExecutor (/Users/isaacmurchie/Downloads/isaacmurchie-macbook-pro-2-2019-04-16-13-58-53/node_modules/appium/node_modules/appium-base-driver/lib/basedriver/driver.js:328:23)
Using AI Code Generation
1const wd = require('wd');2const assert = require('assert');3const chai = require('chai');4const chaiAsPromised = require('chai-as-promised');5chai.use(chaiAsPromised);6chai.should();7const caps = {
Using AI Code Generation
1const { remote } = require('webdriverio');2const opts = {3 capabilities: {4 }5};6(async () => {7 const client = await remote(opts);8 await client.lock(2);9 await client.deleteSession();10})();11const { remote } = require('webdriverio');12const opts = {13 capabilities: {14 }15};16(async () => {17 const client = await remote(opts);18 await client.lock(2);19 await client.deleteSession();20})();21const { remote } = require('webdriverio');22const opts = {23 capabilities: {24 }25};26(async () => {27 const client = await remote(opts);28 await client.lock(2);29 await client.deleteSession();30})();31const { remote } = require('webdriverio');32const opts = {33 capabilities: {34 }35};36(async () => {37 const client = await remote(opts);38 await client.lock(2);39 await client.deleteSession();40})();41const { remote } = require('webdriverio');42const opts = {
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 config = {7};8const driver = wd.promiseChainRemote(config);9const desiredCaps = {10};11driver.init(desiredCaps)12 .then(() => {13 return driver.lock();14 })15 .then(() => {16 return driver.isLocked();17 })18 .then((isLocked) => {19 console.log('Device is locked: ' + isLocked);20 })21 .catch((err) => {22 console.log(err);23 })24 .finally(() => {25 return driver.quit();26 });27driver.unlock();28const wd = require('wd');29const chai = require('chai');30const chaiAsPromised = require('chai-as-promised');31chai.use(chaiAsPromised);32const expect = chai.expect;33const config = {34};35const driver = wd.promiseChainRemote(config);36const desiredCaps = {37};38driver.init(desiredCaps)39 .then(() => {40 return driver.lock();41 })42 .then(() => {43 return driver.isLocked();44 })45 .then((isLocked) => {46 console.log('Device is locked: ' + isLocked);47 return driver.unlock();48 })49 .then(() => {50 return driver.isLocked();51 })52 .then((isLocked) => {53 console.log('Device is locked: ' + isLocked);54 })55 .catch((err) => {56 console.log(err);
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!!