Best JavaScript code snippet using appium-android-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
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 },5};6var driver = webdriverio.remote(options);7 .init()8 .then(function () {9 return driver.lock(5);10 })11 .then(function () {12 return driver.unlock();13 })14 .then(function () {15 return driver.end();16 })17 .catch(function (err) {18 console.log(err);19 });20driver.lock(5)21 .then(function () {22 return driver.unlock();23 })24 .then(function () {25 return driver.end();26 })27 .catch(function (err) {28 console.log(err);29 });30driver.lock(5)31 .then(function () {32 return driver.unlock();33 })34 .then(function () {35 return driver.end();36 })37 .catch(function (err) {38 console.log(err);39 });40driver.lock(5)41 .then(function () {42 return driver.unlock();43 })44 .then(function () {45 return driver.end();46 })47 .catch(function (err) {48 console.log(err);49 });50driver.lock(5)51 .then(function () {52 return driver.unlock();53 })54 .then(function () {55 return driver.end();56 })57 .catch(function (err) {58 console.log(err);59 });60driver.lock(5)61 .then(function () {62 return driver.unlock();63 })64 .then(function () {65 return driver.end();66 })67 .catch(function (err) {68 console.log(err);69 });70driver.lock(5)71 .then(function () {72 return driver.unlock();73 })74 .then(function () {75 return driver.end();76 })77 .catch(function (err) {78 console.log(err);79 });80driver.lock(5)81 .then(function () {82 return driver.unlock();83 })84 .then(function () {85 return driver.end();86 })87 .catch(function (err) {
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var By = webdriver.By;3var until = webdriver.until;4var driver = new webdriver.Builder()5.forBrowser('chrome')6.build();7driver.findElement(By.name('q')).sendKeys('webdriver');8driver.findElement(By.name('btnG')).click();9driver.wait(until.titleIs('webdriver - Google Search'), 1000);10driver.quit();11driver.lock(5);12driver.lock(5).then(function(){13 console.log("Device is locked");14});15driver.lock(5).then(function(){16 console.log("Device is locked");17}, function(err){18 console.log("Error message: " + err);19});20driver.lock(5).then(function(){21 console.log("Device is locked");22}, function(err){23 console.log("Error message: " + err);24}).then(function(){25 console.log("Device is locked");26}, function(err){27 console.log("Error message: " + err);28});29driver.lock(5).then(function(){30 console.log("Device is locked");31}, function(err){32 console.log("Error message: " + err);33}).then(function(){34 console.log("Device is locked");35}, function(err){36 console.log("Error message: " + err);37}).then(function(){38 console.log("Device is locked");39}, function(err){40 console.log("Error message: " + err);41});42driver.lock(5).then(function(){43 console.log("Device is locked");44}, function(err){45 console.log("Error message: " + err);46}).then(function(){47 console.log("Device is locked");48}, function(err){49 console.log("Error message: " + err);50}).then(function(){51 console.log("Device is locked");52}, function(err){53 console.log("Error message: " + err);54}).then(function(){55 console.log("Device is locked");56}, function(err){57 console.log("Error message: " + err);58});59driver.lock(5).then(function
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 .sleep(10000)8 .elementByAccessibilityId('button1')9 .click()10 .sleep(10000)11 .elementByAccessibilityId('button2')12 .click()13 .sleep(10000)14 .elementByAccessibilityId('button3')15 .click()16 .sleep(10000)17 .elementByAccessibilityId('button4')18 .click()19 .sleep(10000)20 .elementByAccessibilityId('button5')21 .click()22 .sleep(10000)23 .elementByAccessibilityId('button6')24 .click()25 .sleep(10000)26 .elementByAccessibilityId('button7')27 .click()28 .sleep(10000)29 .elementByAccessibilityId('button8')30 .click()31 .sleep(10000)32 .elementByAccessibilityId('button9')33 .click()34 .sleep(10000)35 .elementByAccessibilityId('button0')36 .click()37 .sleep(10000)38 .elementByAccessibilityId('buttonClear')39 .click()40 .sleep(10000)41 .elementByAccessibilityId('button1')42 .click()43 .sleep(10000)44 .elementByAccessibilityId('button2')45 .click()46 .sleep(10000)47 .elementByAccessibilityId('button3')48 .click()49 .sleep(10000)50 .elementByAccessibilityId('button4')51 .click()52 .sleep(10000)53 .elementByAccessibilityId('button5')54 .click()55 .sleep(10000)56 .elementByAccessibilityId('button6')57 .click()58 .sleep(10000)59 .elementByAccessibilityId('button7')60 .click()61 .sleep(10000)62 .elementByAccessibilityId('button8')63 .click()
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var asserters = wd.asserters;4var desired = {5};6var driver = wd.promiseChainRemote('localhost', 4723);7 .init(desired)8 .elementByName('Add Contact')9 .click()10 .elementByName('Save')11 .click()12 .elementByClassName('android.widget.EditText')13 .sendKeys('Appium User')14 .elementByName('Save')15 .click()16 .elementByName('Add Contact')17 .click()18 .elementByName('Save')19 .click()20 .elementByClassName('android.widget.EditText')21 .sendKeys('Appium User')22 .elementByName('Save')23 .click()24 .elementsByClassName('android.widget.TextView')25 .then(function (els) {26 return els[1].text();27 })28 .then(function (text) {29 assert.equal(text, 'Appium User');30 })31 .fin(function() { return driver.quit(); })32 .done();33var wd = require('wd');34var assert = require('assert');35var asserters = wd.asserters;36var desired = {37};38var driver = wd.promiseChainRemote('localhost', 4723);39 .init(desired)40 .elementByName('Add Contact')41 .click()42 .elementByName('Save')43 .click()44 .elementByClassName('android.widget.EditText')45 .sendKeys('Appium User')46 .elementByName('Save')47 .click()48 .elementByName('Add Contact')49 .click()50 .elementByName('Save')
Using AI Code Generation
1driver.lock(10);2driver.unlock();3driver.isLocked();4driver.pressKeyCode(66);5driver.longPressKeyCode(66);6driver.currentActivity();7driver.startActivity('com.android.settings', '.Settings');8driver.getDeviceTime();9driver.getPerformanceData('com.android.systemui', 'memoryinfo', 1000);10driver.getPerformanceDataTypes('com.android.systemui');11driver.getSupportedPerformanceDataTypes();12driver.getSystemBars();13driver.hideKeyboard();14driver.isKeyboardShown();15driver.pushFile('/sdcard/test.txt', 'Hello World');16driver.pullFile('/sdcard/test.txt');17driver.pullFolder('/sdcard');18driver.toggleWiFi();19driver.toggleData();
Using AI Code Generation
1var wd = require('wd'),2 assert = require('assert'),3 _ = require('underscore'),4 path = require('path'),5 serverConfigs = require('./helpers/appium-servers');6var serverConfig = serverConfigs.local;7var driver = wd.promiseChainRemote(serverConfig);8var desired = {9 app: path.resolve(__dirname, '../apps/ApiDemos-debug.apk'),10};11 .init(desired)12 .elementByName('App')13 .click()14 .elementByName('Activity')15 .click()16 .elementByName('Custom Title')17 .click()18 .elementByName('Custom Title')19 .lock()20 .elementByName('Custom Title')21 .click()22 .sleep(1000)23 .quit();24driver.unlock();25 .init(desired)26 .elementByName('App')27 .click()28 .elementByName('Activity')29 .click()30 .elementByName('Custom Title')31 .click()32 .elementByName('Custom Title')33 .lock()34 .elementByName('Custom Title')35 .click()36 .sleep(1000)37 .quit();38driver.quit();
Using AI Code Generation
1driver.lock(5);2driver.unlock();3driver.isLocked();4driver.pressKeyCode(4);5driver.longPressKeyCode(4);6driver.hideKeyboard();7driver.resetApp();8driver.installApp("Path to the application to be installed");9driver.removeApp("Package name of the app to be removed");10driver.isAppInstalled("Package name of the app to be checked");11driver.launchApp();12driver.closeApp();13driver.startActivity("com.android.settings", ".Settings");14driver.currentActivity();15driver.backgroundApp(5);16driver.pullFile("/data/local/tmp/strings.json");
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!!