Best JavaScript code snippet using appium-base-driver
gesture.js
Source:gesture.js
...54 .filter((innerAction) => !(innerAction.type === 'pause' && innerAction.duration === 0));55 return modifiedAction;56 });57 log.debug(`Preprocessed actions: ${JSON.stringify(preprocessedActions, null, ' ')}`);58 return await this.proxyCommand('/actions', 'POST', {actions: preprocessedActions});59};60commands.performTouch = async function (gestures) {61 log.debug(`Received the following touch action: ${gesturesChainToString(gestures)}`);62 return await this.proxyCommand('/wda/touch/perform', 'POST', {actions: gestures});63};64commands.performMultiAction = async function (actions) {65 log.debug(`Received the following multi touch action:`);66 for (let i in actions) {67 log.debug(` ${parseInt(i, 10)+1}: ${_.map(actions[i], 'action').join('-')}`);68 }69 return await this.proxyCommand('/wda/touch/multi/perform', 'POST', {actions});70};71commands.nativeClick = async function (el) {72 el = util.unwrapElement(el);73 let endpoint = `/element/${el}/click`;74 return await this.proxyCommand(endpoint, 'POST', {});75};76/*77 * See https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Commands/FBElementCommands.m78 * to get the info about available WDA gestures API79 *80 * See https://developer.apple.com/reference/xctest/xcuielement and81 * https://developer.apple.com/reference/xctest/xcuicoordinate to get the detailed description of82 * all XCTest gestures83*/84helpers.mobileScroll = async function (opts={}, swipe=false) {85 if (!opts.element) {86 opts.element = await this.findNativeElementOrElements(`class name`, `XCUIElementTypeApplication`, false);87 }88 // WDA supports four scrolling strategies: predication based on name, direction,89 // predicateString, and toVisible, in that order. Swiping requires direction.90 let params = {};91 if (opts.name && !swipe) {92 params.name = opts.name;93 } else if (opts.direction) {94 if (['up', 'down', 'left', 'right'].indexOf(opts.direction.toLowerCase()) < 0) {95 let msg = 'Direction must be up, down, left or right';96 log.errorAndThrow(msg);97 }98 params.direction = opts.direction;99 } else if (opts.predicateString && !swipe) {100 params.predicateString = opts.predicateString;101 } else if (opts.toVisible && !swipe) {102 params.toVisible = opts.toVisible;103 } else {104 let msg = swipe ? 'Mobile swipe requires direction' : 'Mobile scroll supports the following strategies: name, direction, predicateString, and toVisible. Specify one of these';105 log.errorAndThrow(msg);106 }107 // we can also optionally pass a distance which appears to be a ratio of108 // screen height, so 1.0 means a full screen's worth of scrolling109 if (!swipe && opts.distance) {110 params.distance = opts.distance;111 }112 let element = opts.element.ELEMENT || opts.element;113 let endpoint = `/wda/element/${element}/${swipe ? 'swipe' : 'scroll'}`;114 return await this.proxyCommand(endpoint, 'POST', params);115};116helpers.mobileSwipe = async function (opts={}) {117 return await this.mobileScroll(opts, true);118};119function parseFloatParameter (paramName, paramValue, methodName) {120 if (_.isUndefined(paramValue)) {121 log.errorAndThrow(`"${paramName}" parameter is mandatory for "${methodName}" call`);122 }123 const result = parseFloat(paramValue);124 if (isNaN(result)) {125 log.errorAndThrow(`"${paramName}" parameter should be a valid number. "${paramValue}" is given instead`);126 }127 return result;128}129helpers.mobilePinch = async function (opts={}) {130 if (!opts.element) {131 opts.element = await this.findNativeElementOrElements(`class name`, `XCUIElementTypeApplication`, false);132 }133 const params = {134 scale: parseFloatParameter('scale', opts.scale, 'pinch'),135 velocity: parseFloatParameter('velocity', opts.velocity, 'pinch')136 };137 const el = opts.element.ELEMENT || opts.element;138 return await this.proxyCommand(`/wda/element/${el}/pinch`, 'POST', params);139};140helpers.mobileDoubleTap = async function (opts={}) {141 if (opts.element) {142 // Double tap element143 const el = opts.element.ELEMENT || opts.element;144 return await this.proxyCommand(`/wda/element/${el}/doubleTap`, 'POST');145 }146 // Double tap coordinates147 const params = {148 x: parseFloatParameter('x', opts.x, 'doubleTap'),149 y: parseFloatParameter('y', opts.y, 'doubleTap')150 };151 return await this.proxyCommand('/wda/doubleTap', 'POST', params);152};153helpers.mobileTwoFingerTap = async function (opts={}) {154 if (!opts.element) {155 opts.element = await this.findNativeElementOrElements(`class name`, `XCUIElementTypeApplication`, false);156 }157 const el = opts.element.ELEMENT || opts.element;158 return await this.proxyCommand(`/wda/element/${el}/twoFingerTap`, 'POST');159};160helpers.mobileTouchAndHold = async function (opts={}) {161 let params = {162 duration: parseFloatParameter('duration', opts.duration, 'touchAndHold')163 };164 if (opts.element) {165 // Long tap element166 const el = opts.element.ELEMENT || opts.element;167 return await this.proxyCommand(`/wda/element/${el}/touchAndHold`, 'POST', params);168 }169 // Long tap coordinates170 params.x = parseFloatParameter('x', opts.x, 'touchAndHold');171 params.y = parseFloatParameter('y', opts.y, 'touchAndHold');172 return await this.proxyCommand('/wda/touchAndHold', 'POST', params);173};174helpers.mobileTap = async function (opts={}) {175 const params = {176 x: parseFloatParameter('x', opts.x, 'tap'),177 y: parseFloatParameter('y', opts.y, 'tap')178 };179 const el = opts.element ? (opts.element.ELEMENT || opts.element) : '0';180 return await this.proxyCommand(`/wda/tap/${el}`, 'POST', params);181};182helpers.mobileDragFromToForDuration = async function (opts={}) {183 const params = {184 duration: parseFloatParameter('duration', opts.duration, 'dragFromToForDuration'),185 fromX: parseFloatParameter('fromX', opts.fromX, 'dragFromToForDuration'),186 fromY: parseFloatParameter('fromY', opts.fromY, 'dragFromToForDuration'),187 toX: parseFloatParameter('toX', opts.toX, 'dragFromToForDuration'),188 toY: parseFloatParameter('toY', opts.toY, 'dragFromToForDuration')189 };190 if (opts.element) {191 // Drag element192 const el = opts.element.ELEMENT || opts.element;193 return await this.proxyCommand(`/wda/element/${el}/dragfromtoforduration`, 'POST', params);194 }195 // Drag coordinates196 return await this.proxyCommand('/wda/dragfromtoforduration', 'POST', params);197};198helpers.mobileSelectPickerWheelValue = async function (opts={}) {199 if (!opts.element) {200 log.errorAndThrow('Element id is expected to be set for selectPickerWheelValue method');201 }202 if (!_.isString(opts.order) || ['next', 'previous'].indexOf(opts.order.toLowerCase()) === -1) {203 log.errorAndThrow(`The mandatory "order" parameter is expected to be equal either to 'next' or 'previous'. ` +204 `'${opts.order}' is given instead`);205 }206 const el = opts.element.ELEMENT || opts.element;207 const params = {order: opts.order};208 if (opts.offset) {209 params.offset = parseFloatParameter('offset', opts.offset, 'selectPickerWheelValue');210 }211 return await this.proxyCommand(`/wda/pickerwheel/${el}/select`, 'POST', params);212};213helpers.getCoordinates = async function (gesture) {214 let el = gesture.options.element;215 // defaults216 let coordinates = {x: 0, y: 0, areOffsets: false};217 let optionX = null;218 if (gesture.options.x) {219 optionX = parseFloatParameter('x', gesture.options.x, 'getCoordinates');220 }221 let optionY = null;222 if (gesture.options.y) {223 optionY = parseFloatParameter('y', gesture.options.y, 'getCoordinates');224 }225 // figure out the element coordinates....
element.js
Source:element.js
...8Object.assign(extensions, iosCommands.element);9commands.getAttribute = async function (attribute, el) {10 el = util.unwrapElement(el);11 if (!this.isWebContext()) {12 let value = await this.proxyCommand(`/element/${el}/attribute/${attribute}`, 'GET');13 // Transform the result for the case when WDA returns an integer representation for a boolean value14 if ([0, 1].indexOf(value) !== -1) {15 value = !!value;16 }17 // The returned value must be of type string according to https://www.w3.org/TR/webdriver/#get-element-attribute18 return (_.isNull(value) || _.isString(value)) ? value : JSON.stringify(value);19 }20 let atomsElement = this.getAtomsElement(el);21 if (_.isNull(atomsElement)) {22 throw new errors.UnknownError(`Error converting element ID for using in WD atoms: '${el}`);23 }24 return await this.executeAtom('get_attribute_value', [atomsElement, attribute]);25};26commands.getText = async function (el) {27 el = util.unwrapElement(el);28 if (!this.isWebContext()) {29 return await this.proxyCommand(`/element/${el}/text`, 'GET');30 }31 let atomsElement = this.useAtomsElement(el);32 return await this.executeAtom('get_text', [atomsElement]);33};34commands.getRect = async function (el) {35 el = util.unwrapElement(el);36 if (this.isWebContext()) {37 throw new errors.NotYetImplementedError('Support for getRect for webcontext is not yet implemented. Please contact an Appium dev');38 }39 return await this.getNativeRect(el);40};41extensions.getNativeRect = async function (el) {42 return await this.proxyCommand(`/element/${el}/rect`, 'GET');43};44commands.getLocation = async function (el) {45 el = el.ELEMENT ? el.ELEMENT : el;46 if (this.isWebContext()) {47 const atomsElement = await this.useAtomsElement(el);48 let loc = await this.executeAtom('get_top_left_coordinates', [atomsElement]);49 if (this.opts.absoluteWebLocations) {50 const script = 'return [document.body.scrollLeft, document.body.scrollTop];';51 const [xOffset, yOffset] = await this.execute(script);52 loc.x += xOffset;53 loc.y += yOffset;54 }55 return loc;56 } else {57 let rect = await this.getRect(el);58 return {x: rect.x, y: rect.y};59 }60};61commands.getLocationInView = async function (el) {62 return await this.getLocation(el);63};64commands.getSize = async function (el) {65 el = el.ELEMENT ? el.ELEMENT : el;66 if (this.isWebContext()) {67 let atomsElement = this.getAtomsElement(el);68 if (atomsElement === null) {69 throw new errors.UnknownError(`Error converting element ID for using in WD atoms: '${el}'`);70 } else {71 return await this.executeAtom('get_size', [atomsElement]);72 }73 } else {74 let rect = await this.getRect(el);75 return {width: rect.width, height: rect.height};76 }77};78function hasSpecialKeys (keys) {79 for (let char of keys) {80 if (isSpecialKey(char)) {81 return true;82 }83 }84 return false;85}86function isSpecialKey (k) {87 if (k === '\uE003' || k === '\ue017') { // BACKSPACE or DELETE88 return true;89 } else if (k === '\uE006' || k === '\uE007') { // RETURN or ENTER90 return true;91 }92 return false;93}94function translateKey (k) {95 if (k === '\uE006' || k === '\uE007') { // RETURN or ENTER96 return '\n';97 } else if (k === '\uE003' || k === '\ue017') { // BACKSPACE or DELETE98 return '\b';99 }100 return k;101}102extensions.bringUpKeyboard = async function (element) {103 // sometimes input is attempted before we have a keyboard. Try to bring one up104 // but we want to handle the retries on find105 let implicitWaitMs = this.implicitWaitMs;106 await this.setImplicitWait(0);107 try {108 await retryInterval(10, 10, async () => {109 try {110 await this.findNativeElementOrElements('class name', 'XCUIElementTypeKeyboard', false);111 log.debug('Keyboard found. Continuing with text input.');112 } catch (err) {113 // no keyboard found114 log.debug('No keyboard found. Clicking element to open it.');115 await this.nativeClick(element);116 await this.findNativeElementOrElements('class name', 'XCUIElementTypeKeyboard', false);117 }118 });119 } finally {120 // no matter what we do, make sure we have the implicit wait set up correctly121 await this.setImplicitWait(implicitWaitMs);122 }123};124commands.setValueImmediate = async function (value, el) {125 // WDA does not provide no way to set the value directly126 log.info('There is currently no way to bypass typing using XCUITest. Setting value through keyboard');127 await this.setValue(value, el);128};129commands.setValue = async function (value, el) {130 el = util.unwrapElement(el);131 if (this.isWebContext()) {132 let atomsElement = this.useAtomsElement(el);133 await this.executeAtom('click', [atomsElement]);134 await this.executeAtom('type', [atomsElement, value]);135 } else {136 const setFormattedValue = async (input, isKeyboardPresenceCheckEnabled) => {137 if (typeof input !== 'string' && !(input instanceof Array)) {138 input = input.toString().split('');139 }140 try {141 await this.proxyCommand(`/element/${el}/value`, 'POST', {value: input});142 } catch (err) {143 // make sure there is a keyboard if this is a text field144 if (isKeyboardPresenceCheckEnabled && await this.getAttribute('type', el) === 'XCUIElementTypeTextField') {145 log.info(`Cannot type in the text field because of ${err}.\nTrying to apply a workaround...`);146 await this.bringUpKeyboard(el);147 await this.proxyCommand(`/element/${el}/value`, 'POST', {value: input});148 } else {149 throw err;150 }151 }152 };153 // possible values of `value`:154 // ['some text']155 // ['s', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't']156 // 'some text'157 if (_.isNull(value) || _.isUndefined(value) || _.isPlainObject(value)) {158 throw new Error(`Only strings and arrays of strings are supported as input arguments. Received: '${JSON.stringify(value)}'`);159 }160 if (_.isArray(value)) {161 // make sure that all the strings inside are a single character long162 value = _.flatMap(value, (v) => (_.isString(v) ? v : JSON.stringify(v)).split(''));163 } else {164 // make it into an array of characters165 value = (value || '').toString().split('');166 }167 if (!hasSpecialKeys(value)) {168 // nothing special, so just send it in169 await setFormattedValue(value, true);170 return;171 }172 // if there are special characters, go through the value until we get to one,173 // and then print it individually174 // currently only supporting return, enter, backspace, and delete175 let buffer = [];176 let isFirstChar = true;177 for (let k of value) {178 let char = translateKey(k);179 if (char === k) {180 buffer.push(char);181 continue;182 }183 // write and clear the buffer184 await setFormattedValue(buffer, isFirstChar);185 isFirstChar = false;186 buffer = [];187 // write the character188 await setFormattedValue([char], isFirstChar);189 }190 // finally, send anything that might be left191 if (buffer.length) {192 await setFormattedValue(buffer, false);193 }194 }195};196commands.keys = async function (value) {197 if (_.isArray(value)) {198 // concatenate any individual strings199 value = value.join('');200 }201 if (_.isString(value)) {202 // split into component characters203 value = value.split('');204 }205 let buffer = [];206 for (let k of value) {207 let char = translateKey(k);208 buffer.push(char);209 }210 await this.proxyCommand('/wda/keys', 'POST', {value: buffer});211};212commands.clear = async function (el) {213 el = util.unwrapElement(el);214 if (this.isWebContext()) {215 let atomsElement = this.useAtomsElement(el);216 await this.executeAtom('clear', [atomsElement]);217 return;218 }219 await retry(5, this.proxyCommand.bind(this), `/element/${el}/clear`, 'POST');220};221Object.assign(extensions, commands);222export { commands };...
general.js
Source:general.js
...7commands.active = async function () {8 if (this.isWebContext()) {9 return await this.executeAtom('active_element', []);10 }11 return await this.proxyCommand(`/element/active`, 'GET');12};13/**14 * Close app (simulate device home button). It is possible to restore15 * the app after the timeout or keep it minimized based on the parameter value.16 *17 * Possible values for `duration`:18 * - any positive number of seconds: come back after X seconds, show deprecation warning19 * - any negative number of seconds: never come back, show deprecation warning20 * - undefined: come back after the default timeout (defined by WDA), show deprecation warning. After deprecation: never come back21 * - {timeout: 5000}: come back after 5 seconds22 * - {timeout: null}, {timeout: -2}: never come back23 */24commands.background = async function (duration) {25 const homescreenEndpoint = '/wda/homescreen';26 const deactivateAppEndpoint = '/wda/deactivateApp';27 let endpoint;28 let params;29 if (_.isUndefined(duration)) {30 // TODO: Replace the block after deprecated stuff is removed31 // endpoint = homescreenEndpoint;32 log.warn('commands.background: Application under test will never be restored in the future if no duration is provided. ' +33 'See https://github.com/appium/appium/issues/7741');34 endpoint = deactivateAppEndpoint;35 params = {};36 } else if (_.isNumber(duration)) {37 // TODO: deprecate this case38 log.warn('commands.background: Passing numbers to \'duration\' argument is deprecated. ' +39 'See https://github.com/appium/appium/issues/7741');40 if (duration >= 0) {41 params = {duration};42 endpoint = deactivateAppEndpoint;43 } else {44 endpoint = homescreenEndpoint;45 }46 } else if (_.isPlainObject(duration)) {47 if (_.has(duration, 'timeout')) {48 if (duration.timeout === null) {49 endpoint = homescreenEndpoint;50 } else if (_.isNumber(duration.timeout)) {51 if (duration.timeout >= 0) {52 params = {duration: duration.timeout / 1000.0};53 endpoint = deactivateAppEndpoint;54 } else {55 endpoint = homescreenEndpoint;56 }57 }58 }59 }60 if (_.isUndefined(endpoint)) {61 log.errorAndThrow('commands.background: Argument value is expected to be an object or \'undefined\'. ' +62 `'${duration}' value has been provided instead. ` +63 'The \'timeout\' attribute can be \'null\' or any negative number to put the app under test ' +64 'into background and never come back or a positive number of milliseconds to wait until the app is restored.');65 }66 return await this.proxyCommand(endpoint, 'POST', params, endpoint !== homescreenEndpoint);67};68commands.touchId = async function (match = true) {69 await this.mobileSendBiometricMatch({match});70};71commands.toggleEnrollTouchId = async function (isEnabled = true) {72 await this.mobileEnrollBiometric({isEnabled});73};74helpers.getWindowSizeWeb = async function getWindowSizeWeb () {75 return await this.executeAtom('get_window_size', []);76};77helpers.getWindowSizeNative = async function getWindowSizeNative () {78 return await this.proxyCommand(`/window/size`, 'GET');79};80commands.getWindowSize = async function (windowHandle = 'current') {81 if (windowHandle !== 'current') {82 throw new errors.NotYetImplementedError('Currently only getting current window size is supported.');83 }84 if (!this.isWebContext()) {85 return await this.getWindowSizeNative();86 } else {87 return await this.getWindowSizeWeb();88 }89};90// For W3C91commands.getWindowRect = async function () {92 const {width, height} = await this.getWindowSize();93 return {94 width,95 height,96 x: 0,97 y: 098 };99};100commands.hideKeyboard = async function (strategy, ...possibleKeys) {101 if (!(this.opts.deviceName || '').includes('iPhone')) {102 // TODO: once WDA can handle dismissing keyboard for iphone, take away conditional103 try {104 await this.proxyCommand('/wda/keyboard/dismiss', 'POST');105 return;106 } catch (err) {107 log.debug('Cannot dismiss the keyboard using the native call. Trying to apply a workaround...');108 }109 }110 let keyboard;111 try {112 keyboard = await this.findNativeElementOrElements('class name', 'XCUIElementTypeKeyboard', false);113 } catch (err) {114 // no keyboard found115 log.debug('No keyboard found. Unable to hide.');116 return;117 }118 possibleKeys.pop(); // last parameter is the session id119 possibleKeys = possibleKeys.filter((element) => !!element); // get rid of undefined elements120 if (possibleKeys.length) {121 for (let key of possibleKeys) {122 let el = _.last(await this.findNativeElementOrElements('accessibility id', key, true, keyboard));123 if (el) {124 log.debug(`Attempting to hide keyboard by pressing '${key}' key.`);125 await this.nativeClick(el);126 return;127 }128 }129 } else {130 // find the keyboard, and hit the last Button131 log.debug('Finding keyboard and clicking final button to close');132 if (await this.getNativeAttribute('visible', keyboard) === 'false') {133 log.debug('No visible keyboard found. Returning');134 return;135 }136 let buttons = await this.findNativeElementOrElements('class name', 'XCUIElementTypeButton', true, keyboard);137 await this.nativeClick(_.last(buttons));138 }139};140commands.getDeviceTime = iosCommands.general.getDeviceTime;141commands.getStrings = iosCommands.general.getStrings;142commands.removeApp = async function (bundleId) {143 return await this.mobileRemoveApp({bundleId});144};145commands.launchApp = iosCommands.general.launchApp;146commands.closeApp = iosCommands.general.closeApp;147commands.keys = async function (keys) {148 if (!this.isWebContext()) {149 throw new errors.UnknownError('Command should be proxied to WDA');150 }151 let el = await this.active();152 if (_.isUndefined(el.ELEMENT)) {153 throw new errors.NoSuchElementError();154 }155 await this.setValue(keys, el.ELEMENT);156};157commands.setUrl = async function (url) {158 if (!this.isWebContext() && this.isRealDevice()) {159 return await this.proxyCommand('/url', 'POST', {url});160 }161 return await iosCommands.general.setUrl.call(this, url);162};163commands.getViewportRect = iosCommands.device.getViewportRect;164// memoized in constructor165commands.getScreenInfo = async function () {166 return await this.proxyCommand('/wda/screen', 'GET');167};168commands.getStatusBarHeight = async function () {169 const {statusBarSize} = await this.getScreenInfo();170 return statusBarSize.height;171};172// memoized in constructor173commands.getDevicePixelRatio = async function () {174 const {scale} = await this.getScreenInfo();175 return scale;176};177commands.mobilePressButton = async function (opts = {}) {178 const {name} = opts;179 if (!name) {180 log.errorAndThrow('Button name is mandatory');181 }182 return await this.proxyCommand('/wda/pressButton', 'POST', {name});183};184commands.mobileSiriCommand = async function (opts = {}) {185 const {text} = opts;186 if (!util.hasValue(text)) {187 log.errorAndThrow('"text" argument is mandatory');188 }189 return await this.proxyCommand('/wda/siri/activate', 'POST', {text});190};191Object.assign(extensions, commands, helpers);192export { commands, helpers, extensions };...
controllers.js
Source:controllers.js
...59 yield this.adb.shell(cmd);60 return null;61};62controllers.url = function * () {63 const result = yield this.proxyCommand('/wd/hub/session/:sessionId/url', 'get', null);64 return result.value;65};66controllers.back = function * () {67 yield this.adb.goBack();68 return null;69};70controllers.tap = function(action) {71 return this72 .proxyCommand('/wd/hub/session/:sessionId/touch/click', 'post', {73 element: action.element74 }).then(result => {75 return _.parseWebDriverResult(result);76 });77};78controllers.keys = function * (value) {79 value = value.join('');80 var arrText = [];81 for (var i = 0; i < value.length; i++) {82 var key = value.charAt(i);83 const keyEvent = keyMap[key];84 if (keyEvent) {85 // update for situation like : xxdd\uE00786 // the enter will go before real content.87 if (arrText.length) {88 yield this.proxyCommand('/wd/hub/session/:sessionId/element/1/value', 'post', {89 value: [arrText.join('')]90 });91 arrText = [];92 }93 yield this.proxyCommand('/wd/hub/session/:sessionId/keys', 'post', {94 value: [keyEvent]95 });96 } else {97 arrText.push(key);98 }99 }100 if (arrText.length) {101 yield this.proxyCommand('/wd/hub/session/:sessionId/element/1/value', 'post', {102 value: [arrText.join('')]103 });104 }105 return null;106};107controllers.getSource = function * () {108 if (!this.isWebContext()) {109 yield this.adb.shell(`touch ${ADB.ANDROID_TMP_DIR}/macaca-dump.xml`);110 }111 const result = yield this.proxyCommand('/wd/hub/session/:sessionId/source', 'get', null);112 var xml = result.value;113 if (this.isWebContext() || (!this.isWebContext() && this.chromedriver)) {114 return xml;115 }116 const hierarchy = xml2map.tojson(xml).hierarchy;117 // tojson: if 'node' has only one element, the property will become json object instead of JSONArray118 // for device under Android API 5.0, 'node' is always an single element, and hence need to be wrapped into array119 if (hierarchy.node && !_.isArray(hierarchy.node)) {120 hierarchy.node = [hierarchy.node];121 }122 var res = _.filter(hierarchy.node, i => i.package !== 'com.android.systemui');123 return JSON.stringify(res && res[0] || []);124};125controllers.title = function * () {126 if (!this.isWebContext()) {127 const focusedActivity = yield this.adb.getFocusedActivity();128 return focusedActivity;129 }130 const result = yield this.proxyCommand('/wd/hub/session/:sessionId/title', 'get', null);131 return result.value;132};...
alert.js
Source:alert.js
...7 return text;8 }9 let method = 'GET';10 let endpoint = `/alert/text`;11 return await this.proxyCommand(endpoint, method);12};13// TODO: WDA does not currently support this natively14commands.setAlertText = async function (text) {15 if (!Array.isArray(text)) {16 text = text.split('');17 }18 if (this.isWebContext()) {19 let alert = await this.getAlert();20 await alert.setText(text);21 return;22 }23 let method = 'POST';24 let endpoint = `/alert/text`;25 return await this.proxyCommand(endpoint, method, text);26};27commands.postAcceptAlert = async function () {28 if (this.isWebContext()) {29 let alert = await this.getAlert();30 if (alert.close) {31 await alert.close();32 } else {33 await alert.ok();34 }35 return;36 }37 let method = 'POST';38 let endpoint = `/alert/accept`;39 return await this.proxyCommand(endpoint, method);40};41commands.postDismissAlert = async function () {42 if (this.isWebContext()) {43 let alert = await this.getAlert();44 if (alert.close) {45 await alert.close();46 } else {47 await alert.cancel();48 }49 return;50 }51 let method = 'POST';52 let endpoint = `/alert/dismiss`;53 return await this.proxyCommand(endpoint, method);54};55helpers.getAlert = async function () {56 let possibleAlert = await this.findNativeElementOrElements('class name', 'XCUIElementTypeScrollView', true);57 if (possibleAlert.length !== 1) throw new errors.NoAlertOpenError();58 let possibleAlertButtons = await this.findNativeElementOrElements('class name', 'XCUIElementTypeButton', true, possibleAlert[0].ELEMENT);59 if (possibleAlertButtons.length < 1 || possibleAlertButtons.length > 2) throw new errors.NoAlertOpenError();60 let assertButtonName = async (button, expectedName) => {61 button = button.ELEMENT ? button.ELEMENT : button;62 let name = await this.proxyCommand(`/element/${button}/attribute/name`, 'GET');63 if (name.toLowerCase() !== expectedName) throw new errors.NoAlertOpenError();64 };65 let alert = possibleAlert[0];66 if (possibleAlertButtons.length === 1) {67 // make sure the button is 'Close'68 let closeButton = possibleAlertButtons[0];69 await assertButtonName(closeButton, 'close');70 alert.close = async () => {71 await this.proxyCommand(`/element/${closeButton.ELEMENT}/click`, 'POST');72 };73 } else {74 // ensure the buttons are 'Cancel' and 'OK'75 let cancelButton = possibleAlertButtons[0];76 await assertButtonName(cancelButton, 'cancel');77 let okButton = possibleAlertButtons[1];78 await assertButtonName(okButton, 'ok');79 alert.cancel = async () => {80 await this.proxyCommand(`/element/${cancelButton.ELEMENT}/click`, 'POST');81 };82 alert.ok = async () => {83 await this.proxyCommand(`/element/${okButton.ELEMENT}/click`, 'POST');84 };85 }86 alert.getText = async () => {87 let textView = await this.findNativeElementOrElements('class name', 'XCUIElementTypeTextView', false, alert.ELEMENT);88 return await this.proxyCommand(`/element/${textView.ELEMENT}/attribute/value`, 'GET');89 };90 alert.setText = async (value) => {91 try {92 let textView = await this.findNativeElementOrElements('class name', 'XCUIElementTypeTextField', false, alert.ELEMENT);93 await this.proxyCommand(`/element/${textView.ELEMENT}/value `, 'POST', {value});94 } catch (err) {95 if (isErrorType(err, errors.NoSuchElementError)) {96 throw new Error('Tried to set text of an alert that was not a prompt');97 }98 throw err;99 }100 };101 return alert;102};103Object.assign(extensions, commands, helpers);104export { commands, helpers };...
lock.js
Source:lock.js
1import B from 'bluebird';2let commands = {};3commands.lock = async function (seconds) {4 await this.proxyCommand('/wda/lock', 'POST');5 if (isNaN(seconds)) {6 return;7 }8 const floatSeconds = parseFloat(seconds);9 if (floatSeconds <= 0) {10 return;11 }12 await B.delay(floatSeconds * 1000);13 await this.proxyCommand('/wda/unlock', 'POST');14};15commands.unlock = async function () {16 await this.proxyCommand('/wda/unlock', 'POST');17};18commands.isLocked = async function () {19 return await this.proxyCommand('/wda/locked', 'GET');20};21export { commands };...
Using AI Code Generation
1const { BaseDriver } = require('appium-base-driver');2class MyDriver extends BaseDriver {3 async proxyCommand (url, method, body) {4 return await this.proxyCommand(url, method, body);5 }6}7module.exports = MyDriver;8const { BaseDriver } = require('appium-base-driver');9class MyDriver extends BaseDriver {10 async proxyCommand (url, method, body) {11 return await this.proxyCommand(url, method, body);12 }13 async getDeviceTime () {14 return await this.proxyCommand('/wd/hub/status', 'GET');15 }16}17module.exports = MyDriver;18const { BaseDriver } = require('appium-base-driver');19class MyDriver extends BaseDriver {20 async proxyCommand (url, method, body) {21 return await this.proxyCommand(url, method, body);22 }23 async getDeviceTime () {24 return await this.proxyCommand('/wd/hub/status', 'GET');25 }26 async getTime () {27 const deviceTime = await this.getDeviceTime();28 return deviceTime.uptime;29 }30}31module.exports = MyDriver;32const { BaseDriver } = require('appium-base-driver');33const MyDriver = require('./mydriver');34const driver = new MyDriver();35driver.getTime().then((time) => {36 console.log(time);37});
Using AI Code Generation
1let driver = await wdio.remote({2 capabilities: {3 }4});5await driver.proxyCommand('/session/:sessionId/appium/device/lock', 'POST', {seconds: 5});6async proxyCommand (url, method, body = null) {7 const {sessionId} = this;8 const {protocol, host, port} = this.opts;9 const fullUrl = url.replace(/:sessionId/g, sessionId);10 const opts = {11 };12 if (body) {13 opts.body = body;14 }15 return await request(opts);16}17async proxyCommand (url, method, body = null) {18 const {sessionId} = this;19 const {protocol, host, port} = this.opts;20 const fullUrl = url.replace(/:sessionId/g, sessionId);21 const opts = {22 };23 if (body) {24 opts.body = body;25 }26 return await request(opts);27}28async proxyCommand (url, method, body = null) {29 const {sessionId} = this;30 const {protocol, host, port} = this.opts;31 const fullUrl = url.replace(/:sessionId/g, sessionId);32 const opts = {33 };34 if (body) {35 opts.body = body;36 }37 return await request(opts);38}39async proxyCommand (url,
Using AI Code Generation
1const wd = require('wd');2const { getDriver } = require('appium-base-driver');3const { startServer } = require('appium');4const { AndroidDriver } = require('appium-android-driver');5(async () => {6 const server = await startServer(4723, '
Using AI Code Generation
1const AppiumBaseDriver = require('appium-base-driver');2const {BaseDriver} = AppiumBaseDriver;3const {SubProcess} = AppiumBaseDriver;4const {logger} = AppiumBaseDriver;5const {util} = AppiumBaseDriver;6const {system} = AppiumBaseDriver;7class MyDriver extends BaseDriver {8 async createSession (caps) {9 this.proxyCommand('/session/:sessionId/element/:elementId/click', 'POST');10 return caps;11 }12}13const driver = new MyDriver();14driver.createSession({foo: 'bar'}).then((caps) => {15 console.log(caps);16});17the HTTP method to use (GET, POST, etc)
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desired = {4};5var browser = wd.promiseChainRemote('localhost', 4723);6browser.init(desired).then(function() {7}).then(function() {8 return browser.elementById("lst-ib").type("Hello World!");9}).then(function() {10 return browser.elementById("lst-ib").getValue();11}).then(function(text) {12 assert.equal(text, "Hello World!");13}).fin(function() {14 return browser.quit();15}).done();
Using AI Code Generation
1 console.log('element found', res);2}).catch(function (err) {3 console.log('error', err);4});5 console.log('element found', res);6}).catch(function (err) {7 console.log('error', err);8});9 console.log('element found', res);10}).catch(function (err) {11 console.log('error', err);12});13 console.log('element found', res);14}).catch(function (err) {15 console.log('error', err);16});17 console.log('element found', res);18}).catch(function (err) {19 console.log('error', err);20});21 console.log('element found', res);22}).catch(function (err) {23 console.log('error', err);24});
Using AI Code Generation
1import { BaseDriver } from 'appium-base-driver';2import _ from 'lodash';3import B from 'bluebird';4import request from 'request-promise';5import { JWProxy } from 'appium-base-driver';6const commands = {};7const extensions = {};8commands.proxyCommand = async function (url, method, body) {9 let opts = {10 };11 if (body) {12 opts.body = body;13 }14 return await request(opts);15};16class AppiumDriver extends BaseDriver {17 constructor (opts = {}, shouldValidateCaps = true) {18 super(opts, shouldValidateCaps);19 this.jwproxy = new JWProxy({server: 'localhost', port: 4444});20 }21 async createSession (caps) {22 let sessionId = await super.createSession(caps);23 await this.jwproxy.command('/session', 'POST', {desiredCapabilities: caps});24 return sessionId;25 }26 async deleteSession () {27 await super.deleteSession();28 await this.jwproxy.command('/session', 'DELETE');29 }30 async proxyCommandToMJSONWP (url, method, body) {31 return await this.proxyCommand(url, method, body);32 }33 async proxyCommandToWD (url, method, body) {34 return await this.proxyCommand(url, method, body);35 }36}37Object.assign(AppiumDriver, commands, extensions);38export { AppiumDriver };39export default AppiumDriver;40import { BaseDriver } from 'appium-base-driver';41import _ from 'lodash';42import B from 'bluebird';43import request from 'request-promise';44import { JWProxy } from 'appium-base-driver';45const commands = {};46const extensions = {};47commands.proxyCommand = async function (url, method, body) {48 let opts = {49 };50 if (body)
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!!