Best JavaScript code snippet using appium-base-driver
general.js
Source:general.js
...31 'in order to close and launch the application under test');32};33commands.getClipboard = async function getClipboard () {34 return (await this.adb.getApiLevel() < 29)35 ? (await this.espresso.jwproxy.command('/appium/device/get_clipboard', 'POST', {}))36 : (await this.adb.getClipboard());37};38commands.mobilePerformEditorAction = async function mobilePerformEditorAction (opts = {}) {39 const {action} = assertRequiredOptions(opts, ['action']);40 return await this.espresso.jwproxy.command('/appium/device/perform_editor_action', 'POST', {action});41};42commands.mobileSwipe = async function mobileSwipe (opts = {}) {43 const {direction, element, swiper, startCoordinates, endCoordinates, precisionDescriber} = assertRequiredOptions(opts, ['element']);44 return await this.espresso.jwproxy.command(`/appium/execute_mobile/${util.unwrapElement(element)}/swipe`, 'POST', {45 direction, element, swiper, startCoordinates, endCoordinates, precisionDescriber46 });47};48commands.mobileGetDeviceInfo = async function mobileGetDeviceInfo () {49 return await this.espresso.jwproxy.command('/appium/device/info', 'GET');50};51commands.mobileIsToastVisible = async function mobileIsToastVisible (opts = {}) {52 const {text, isRegexp} = opts;53 if (!util.hasValue(text)) {54 throw new errors.InvalidArgumentError(`'text' argument is mandatory`);55 }56 return await this.espresso.jwproxy.command('/appium/execute_mobile/is_toast_displayed', 'POST', {57 text,58 isRegexp,59 });60};61commands.mobileOpenDrawer = async function mobileOpenDrawer (opts = {}) {62 const {element, gravity} = assertRequiredOptions(opts, ['element']);63 return await this.espresso.jwproxy.command(`/appium/execute_mobile/${util.unwrapElement(element)}/open_drawer`, 'POST', {64 gravity65 });66};67commands.mobileCloseDrawer = async function mobileCloseDrawer (opts = {}) {68 const {element, gravity} = assertRequiredOptions(opts, ['element']);69 return await this.espresso.jwproxy.command(`/appium/execute_mobile/${util.unwrapElement(element)}/close_drawer`, 'POST', {70 gravity71 });72};73commands.mobileSetDate = async function mobileSetDate (opts = {}) {74 const {element, year, monthOfYear, dayOfMonth} = assertRequiredOptions(opts, ['element', 'year', 'monthOfYear', 'dayOfMonth']);75 return await this.espresso.jwproxy.command(`/appium/execute_mobile/${util.unwrapElement(element)}/set_date`, 'POST', {76 year,77 monthOfYear,78 dayOfMonth,79 });80};81commands.mobileSetTime = async function mobileSetTime (opts = {}) {82 const {element, hours, minutes} = assertRequiredOptions(opts, ['element', 'hours', 'minutes']);83 return await this.espresso.jwproxy.command(`/appium/execute_mobile/${util.unwrapElement(element)}/set_time`, 'POST', {84 hours,85 minutes,86 });87};88commands.mobileNavigateTo = async function mobileNavigateTo (opts = {}) {89 let {element, menuItemId} = assertRequiredOptions(opts, ['menuItemId', 'element']);90 let menuItemIdAsNumber = parseInt(menuItemId, 10);91 if (_.isNaN(menuItemIdAsNumber) || menuItemIdAsNumber < 0) {92 throw new errors.InvalidArgumentError(`'menuItemId' must be a non-negative number. Found ${menuItemId}`);93 }94 return await this.espresso.jwproxy.command(`/appium/execute_mobile/${util.unwrapElement(element)}/navigate_to`, 'POST', {95 menuItemId96 });97};98/**99 * Runs a chain of Espresso web atoms (see https://developer.android.com/training/testing/espresso/web for reference)100 *101 * Takes JSON of the form102 *103 * {104 * "webviewEl": "<ELEMENT_ID>", // optional webview element to operate on105 * "forceJavascriptEnabled": true|false, // if webview disables javascript, webatoms won't work, this forces it106 * "methodChain": [107 * {"name": "methodName", "atom": {"name": "atomName", "args": ["arg1", "arg2", ...]}},108 * ...109 * ]110 * }111 *112 */113commands.mobileWebAtoms = async function mobileWebAtoms (opts = {}) {114 opts = assertRequiredOptions(opts, ['methodChain']);115 return await this.espresso.jwproxy.command(`/appium/execute_mobile/web_atoms`, 'POST', opts);116};117commands.getDisplayDensity = async function getDisplayDensity () {118 return await this.espresso.jwproxy.command('/appium/device/display_density', 'GET', {});119};120commands.mobileScrollToPage = async function mobileScrollToPage (opts = {}) {121 // Validate the parameters122 const scrollToTypes = ['first', 'last', 'left', 'right'];123 const res = validate(opts, {124 element: {presence: true},125 scrollTo: {126 inclusion: {127 within: scrollToTypes,128 message: `"scrollTo" must be one of "${scrollToTypes.join(', ')}" found '%{value}'`,129 }130 },131 scrollToPage: {132 numericality: {133 onlyInteger: true,134 greaterThanOrEqualTo: 0,135 message: `"scrollToPage" must be a non-negative integer. Found '%{value}'`136 },137 },138 });139 if (util.hasValue(res)) {140 throw new errors.InvalidArgumentError(`Invalid scrollTo parameters: ${JSON.stringify(res)}`);141 }142 const {element, scrollTo, scrollToPage, smoothScroll} = opts;143 if (util.hasValue(scrollTo) && util.hasValue(scrollToPage)) {144 this.log.warn(`'scrollTo' and 'scrollToPage' where both provided. Defaulting to 'scrollTo'`);145 }146 return await this.espresso.jwproxy.command(`/appium/execute_mobile/${util.unwrapElement(element)}/scroll_to_page`, 'POST', {147 scrollTo,148 scrollToPage,149 smoothScroll,150 });151};152/**153 * API to invoke methods defined in Android app.154 *155 * Example data156 * {157 * target: 'activity',158 * methods:159 * [160 * {161 * name: "someMethod",162 * },163 * {164 * name: "anotherMethod",165 * args:166 * [167 * {value: "Lol", type: 'java.lang.CharSequence'},168 * {value: 1, type: 'int'}169 * ]170 * }171 * ]172 * }173 *174 * In above example, method "someMethod" will be invoked on 'activity'. On the result, "anotherMethod" will be invoked175 * "target" can be either 'activity', 'application' or 'element'176 * If target is set to 'application', methods will be invoked on application class177 * If target is set to 'activity', methods will be invoked on current activity178 * If target is set to 'element', 'elementId' must be specified179 *180 * - Only 'Public' methods can be invoked. ('open' modifire is necessary in Kotlin)181 * - following primitive types are supported: "int", "boolean", "byte", "short", "long", "float", "char"182 * - Non-primitive types with fully qualified name "java.lang.*" is also supported:183 * Eg. "java.lang.CharSequence", "java.lang.String", "java.lang.Integer", "java.lang.Float",184 * "java.lang.Double", "java.lang.Boolean", "java.lang.Long", "java.lang.Short",185 * "java.lang.Character" etc...186 *187 *188 * @throws {Error} if target is not 'activity' or 'application'189 * @throws {Error} if a method is not found with given argument types190 *191 * @return {*} the result of the last method in the invocation chain. If method return type is void, then "<VOID>" will be returned192 *193 */194commands.mobileBackdoor = async function mobileBackdoor (opts = {}) {195 assertRequiredOptions(opts, ['target', 'methods']);196 const {target, methods} = opts;197 if (target === 'element') {198 assertRequiredOptions(opts, ['elementId']);199 }200 const {elementId: targetElement} = opts;201 return await this.espresso.jwproxy.command(`/appium/execute_mobile/backdoor`, 'POST', {target, methods, targetElement});202};203/**204 * Execute UiAutomator2 commands to drive out of app areas.205 * strategy can be one of: "clazz", "res", "text", "textContains", "textEndsWith", "textStartsWith",206 * "desc", "descContains", "descEndsWith", "descStartsWith", "pkg"207 *208 * action can be one of: "click", "longClick", "getText", "getContentDescription", "getClassName",209 * "getResourceName", "getVisibleBounds", "getVisibleCenter", "getApplicationPackage",210 * "getChildCount", "clear", "isCheckable", "isChecked", "isClickable", "isEnabled",211 * "isFocusable", "isFocused", "isLongClickable", "isScrollable", "isSelected"212 */213commands.mobileUiautomator = async function mobileUiautomator (opts = {}) {214 const {strategy, locator, action, index} = assertRequiredOptions(opts, ['strategy', 'locator', 'action']);215 return await this.espresso.jwproxy.command(`/appium/execute_mobile/uiautomator`, 'POST', {strategy, locator, index, action});216};217/**218 * Execute UiAutomator2 command to return the UI dump when AUT is in background.219 * @throws {Error} if uiautomator view dump is unsuccessful220 * @returns {string} uiautomator DOM xml as string221 */222commands.mobileUiautomatorPageSource = async function mobileUiautomatorPageSource () {223 return await this.espresso.jwproxy.command(`/appium/execute_mobile/uiautomator_page_source`, 'GET');224};225/**226 * Flash the element with given id.227 * durationMillis and repeatCount are optional228 *229 */230commands.mobileFlashElement = async function mobileFlashElement (opts = {}) {231 const {element} = assertRequiredOptions(opts, ['element']);232 const {durationMillis, repeatCount} = opts;233 return await this.espresso.jwproxy.command(`/appium/execute_mobile/${util.unwrapElement(element)}/flash`, 'POST', {234 durationMillis,235 repeatCount236 });237};238/**239 * Perform a 'GeneralClickAction' (https://developer.android.com/reference/androidx/test/espresso/action/GeneralClickAction)240 */241commands.mobileClickAction = async function mobileClickAction (opts = {}) {242 const {element, tapper, coordinatesProvider, precisionDescriber,243 inputDevice, buttonState} = assertRequiredOptions(opts, ['element']);244 return await this.espresso.jwproxy.command(`/appium/execute_mobile/${util.unwrapElement(element)}/click_action`, 'POST', {245 tapper, coordinatesProvider, precisionDescriber, inputDevice, buttonState246 });247};248commands.updateSettings = async function updateSettings (settings) {249 return await this.espresso.jwproxy.command(`/appium/settings`, 'POST', { settings });250};251commands.getSettings = async function getSettings () {252 return await this.espresso.jwproxy.command(`/appium/settings`, 'GET');253};254// Stop proxying to any Chromedriver and redirect to Espresso255helpers.suspendChromedriverProxy = function suspendChromedriverProxy () {256 this.chromedriver = null;257 this.proxyReqRes = this.espresso.proxyReqRes.bind(this.espresso);258 this.proxyCommand = this.espresso.proxyCommand.bind(this.espresso);259 this.jwpProxyActive = true;260};261commands.startActivity = async function startActivity (appPackage, appActivity,262 appWaitPackage, appWaitActivity) {263 // intentAction, intentCategory, intentFlags, optionalIntentArguments, dontStopAppOnReset264 // parameters are not supported by Espresso265 appPackage = appPackage || this.caps.appPackage;266 appWaitPackage = appWaitPackage || appPackage;267 appActivity = qualifyActivityName(appActivity, appPackage);268 appWaitActivity = qualifyActivityName(appWaitActivity || appActivity, appWaitPackage);269 this.log.debug(`Starting activity '${appActivity}' for package '${appPackage}'`);270 await this.espresso.jwproxy.command(`/appium/device/start_activity`, 'POST', {271 appPackage,272 appActivity,273 });274 await this.adb.waitForActivity(appWaitPackage, appWaitActivity);275};276commands.mobileDismissAutofill = async function mobileDismissAutofill (opts = {}) {277 const {element} = assertRequiredOptions(opts, ['element']);278 await this.espresso.jwproxy.command(279 `/session/:sessionId/appium/execute_mobile/${util.unwrapElement(element)}/dismiss_autofill`, 'POST', {});280};281Object.assign(extensions, commands, helpers);282export { commands, helpers };...
commands.js
Source:commands.js
...25commands.performMultiAction = async function performMultiAction (elId, actions) {26 if (elId) {27 throw new Error('Selendroid actions do not support element id');28 }29 return await this.selendroid.jwproxy.command('/action', 'POST', {payload: actions});30};31function encodeString (value, unicode) {32 for (let i = 0; i < value.length; i++) {33 let c = value.charCodeAt(i);34 // if we're using the unicode keyboard, and this is unicode, maybe encode35 if (unicode && (c > 127 || c === 38)) {36 // this is not simple ascii, or it is an ampersand (`&`)37 if (c >= parseInt('E000', 16) && c <= parseInt('E040', 16)) {38 // Selenium uses a Unicode PUA to cover certain special characters39 // see https://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/Keys.java40 } else {41 // encode the text42 value = imap.encode(value);43 break;44 }45 }46 }47 return value;48}49// Need to override this for correct unicode support50commands.setValue = async function setValue (value, elementId) {51 if (value instanceof Array) {52 value = value.join('');53 }54 log.debug(`Setting text on element '${elementId}': '${value}'`);55 value = encodeString(value, this.opts.unicodeKeyboard);56 await this.selendroid.jwproxy.command(`/element/${elementId}/value`, 'POST', {value: [value]});57};58// This is needed to satisfy updated WebElement interface in Selenium 359commands.getElementRect = async function getElementRect (elementId) {60 const location = await this.selendroid.jwproxy.command(`/element/${elementId}/location`, 'GET');61 const size = await this.selendroid.jwproxy.command(`/element/${elementId}/size`, 'GET');62 return Object.assign(location, size);63};64// Need to override this for correct unicode support65commands.keys = async function keys (value) {66 if (value instanceof Array) {67 value = value.join('');68 }69 log.debug(`Setting text: '${value}'`);70 value = encodeString(value, this.opts.unicodeKeyboard);71 await this.selendroid.jwproxy.command('/keys', 'POST', {value: [value]});72};73// Selendroid doesn't support metastate for keyevents74commands.keyevent = async function keyevent (keycode, metastate) {75 log.debug(`Ignoring metastate ${metastate}`);76 await this.adb.keyevent(keycode);77};78// Use ADB since we don't have UiAutomator79commands.back = async function back () {80 await this.adb.keyevent(4);81};82commands.getContexts = async function getContexts () {83 let chromiumViews = [];84 let webviews = await webviewHelpers.getWebviews(this.adb,85 this.opts.androidDeviceSocket);86 if (_.includes(webviews, CHROMIUM_WIN)) {87 chromiumViews = [CHROMIUM_WIN];88 } else {89 chromiumViews = [];90 }91 log.info('Getting window handles from Selendroid');92 let selendroidViews = await this.selendroid.jwproxy.command('/window_handles', 'GET', {});93 this.contexts = _.union(selendroidViews, chromiumViews);94 log.info(`Available contexts: ${JSON.stringify(this.contexts)}`);95 return this.contexts;96};97helpers.switchContext = async function switchContext (name) {98 // called when setting context99 await this.selendroid.jwproxy.command('/window', 'POST', {name});100};101helpers.isChromedriverContext = function isChromedriverContext (windowName) {102 return windowName === CHROMIUM_WIN;103};104// Need to override android-driver's version of this since we don't actually105// have a bootstrap; instead we just restart adb and re-forward the Selendroid106// port107helpers.wrapBootstrapDisconnect = async function wrapBootstrapDisconnect (wrapped) {108 await wrapped();109 await this.adb.restart();110 await this.adb.forwardPort(this.opts.systemPort, DEVICE_PORT);111};112Object.assign(extensions, commands, helpers);113export default extensions;
selendroid.js
Source:selendroid.js
...74 await this.adb.instrument(this.appPackage, this.appActivity, instrumentWith);75 logger.info('Waiting for Selendroid to be online...');76 // wait 20s for Selendroid to be online77 await retryInterval(20, 1000, async () => {78 await this.jwproxy.command('/status', 'GET');79 });80 await this.jwproxy.command('/session', 'POST', {desiredCapabilities: caps});81 }82 async deleteSession () {83 logger.debug('Deleting Selendroid server session');84 // rely on jwproxy's intelligence to know what we're talking about and85 // delete the current session86 try {87 await this.jwproxy.command('/', 'DELETE');88 } catch (err) {89 logger.warn(`Did not get confirmation Selendroid deleteSession worked; ` +90 `Error was: ${err}`);91 }92 }93}...
element.js
Source:element.js
...4function toBool (s) {5 return _.isString(s) ? (s.toLowerCase() === 'true') : !!s;6}7commands.getAttribute = async function (attribute, elementId) {8 return await this.uiautomator2.jwproxy.command(`/element/${elementId}/attribute/${attribute}`, 'GET', {});9};10commands.elementDisplayed = async function (elementId) {11 return toBool(await this.getAttribute("displayed", elementId));12};13commands.elementEnabled = async function (elementId) {14 return toBool(await this.getAttribute("enabled", elementId));15};16commands.elementSelected = async function (elementId) {17 return toBool(await this.getAttribute("selected", elementId));18};19commands.getName = async function (elementId) {20 return await this.uiautomator2.jwproxy.command(`/element/${elementId}/name`, 'GET', {});21};22commands.getLocation = async function (elementId) {23 log.info(`calling get location: ${elementId}`);24 return await this.uiautomator2.jwproxy.command(`/element/${elementId}/location`, 'GET', {});25};26commands.getSize = async function (elementId) {27 return await this.uiautomator2.jwproxy.command(`/element/${elementId}/size`, 'GET', {});28};29commands.touchLongClick = async function (element, x, y, duration) {30 let params = {element, x, y, duration};31 return await this.uiautomator2.jwproxy.command(`/touch/longclick`, 'POST', {params});32};33commands.touchDown = async function (element, x, y) {34 let params = {element, x, y};35 return await this.uiautomator2.jwproxy.command(`/touch/down`, 'POST', {params});36};37commands.touchUp = async function (element, x, y) {38 let params = {element, x, y};39 return await this.uiautomator2.jwproxy.command(`/touch/up`, 'POST', {params});40};41commands.touchMove = async function (element, x, y) {42 let params = {element, x, y};43 return await this.uiautomator2.jwproxy.command(`/touch/move`, 'POST', {params});44};45helpers.doSetElementValue = async function (params) {46 return await this.uiautomator2.jwproxy.command(`/element/${params.elementId}/value`, 'POST', params);47};48commands.setValueImmediate = async function (keys, elementId) {49 return await this.uiautomator2.jwproxy.command(`/element/${elementId}/value`, 'POST', {50 elementId,51 text: _.isArray(keys) ? keys.join('') : keys,52 replace: false,53 unicodeKeyboard: this.opts.unicodeKeyboard,54 });55};56commands.getText = async function (elementId) {57 return await this.uiautomator2.jwproxy.command(`/element/${elementId}/text`, 'GET', {});58};59commands.click = async function (element) {60 return await this.uiautomator2.jwproxy.command(`/element/${element}/click`, 'POST', {element});61};62commands.getElementScreenshot = async function (element) {63 return await this.uiautomator2.jwproxy.command(`/element/${element}/screenshot`, 'GET', {});64};65commands.tap = async function (element, x = 0, y = 0, count = 1) {66 for (let i = 0; i < count; i++) {67 if (element) {68 // we are either tapping on the default location of the element69 // or an offset from the top left corner70 let params = {element};71 if (x !== 0 || y !== 0) {72 params.x = x;73 params.y = y;74 }75 await this.uiautomator2.jwproxy.command(`/element/${element}/click`, 'POST', params);76 } else {77 await this.uiautomator2.jwproxy.command(`/appium/tap`, 'POST', {x, y});78 }79 }80};81commands.clear = async function (elementId) {82 return await this.uiautomator2.jwproxy.command(`/element/${elementId}/clear`, 'POST', {elementId});83};84Object.assign(extensions, commands, helpers);85export { commands, helpers };...
driver-specs.js
Source:driver-specs.js
1import sinon from 'sinon';2import { settings as iosSettings } 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 log from '../../lib/logger';9import * as utils from '../../lib/utils';10import request from 'request-promise';11const caps = {platformName: "iOS", deviceName: "iPhone 6", app: "/foo.app"};12const anoop = async () => {};13describe('driver commands', () => {14 let driver = new XCUITestDriver();15 let proxySpy = sinon.stub(driver, 'proxyCommand');16 afterEach(() => {17 proxySpy.reset();18 });19 describe('status caching', () => {20 let d;21 let jwproxyCommandSpy;22 beforeEach(() => {23 d = new XCUITestDriver();24 let fakeProxy = new JWProxy();25 jwproxyCommandSpy = sinon.stub(fakeProxy, "command", async () => {26 return {some: 'thing'};27 });28 d.wda = {jwproxy: fakeProxy};29 });30 afterEach(() => {31 jwproxyCommandSpy.reset();32 });33 it('wda status is not present by default', async () => {34 let status = await d.getStatus();35 jwproxyCommandSpy.calledOnce.should.be.false;36 chai.should().equal(status.wda, undefined);37 });38 it('should cache wda status', async () => {39 d.proxyCommand('/status', 'GET');40 let status = await d.getStatus();41 jwproxyCommandSpy.calledOnce.should.be.true;42 jwproxyCommandSpy.calledTwice.should.be.false;43 status.wda.should.exist;44 });45 });46 describe('createSession', () => {47 let d;48 let sandbox;49 beforeEach(() => {50 d = new XCUITestDriver();51 sandbox = sinon.sandbox.create();52 sandbox.stub(d, "determineDevice", async () => {53 return {54 device: {55 shutdown: anoop,56 stat () {57 return {state: 'Booted'};58 }59 },60 udid: null,61 realDevice: null62 };63 });64 sandbox.stub(d, "configureApp", anoop);65 sandbox.stub(d, "startLogCapture", anoop);66 sandbox.stub(d, "startSim", anoop);67 sandbox.stub(d, "startWdaSession", anoop);68 sandbox.stub(d, "startWda", anoop);69 sandbox.stub(d, "extractBundleId", anoop);70 sandbox.stub(d, "installApp", anoop);71 sandbox.stub(iosSettings, "setLocale", anoop);72 sandbox.stub(iosSettings, "setPreferences", anoop);73 sandbox.stub(xcode, "getMaxIOSSDK", async () => {74 return '10.0';75 });76 sandbox.stub(utils, "checkAppPresent", anoop);77 });78 afterEach(() => {79 sandbox.restore();80 });81 it('should include server capabilities', async () => {82 let resCaps = await d.createSession(caps);83 resCaps[1].javascriptEnabled.should.be.true;84 });85 it('should warn', async () => {86 let warnStub = sinon.stub(log, "warn", async () => {});87 await d.createSession(_.defaults({autoAcceptAlerts: true}, caps));88 warnStub.calledTwice.should.be.true;89 _.filter(warnStub.args, (arg) => arg[0].indexOf('autoAcceptAlerts') !== -1)90 .should.have.length(1);91 warnStub.restore();92 });93 });94 describe('startIWDP()', () => {95 it('should start and stop IWDP server', async () => {96 await driver.startIWDP();97 let endpoint = driver.iwdpServer.endpoint;98 await request(endpoint).should.eventually.have.string('<html');99 await driver.stopIWDP();100 await request(endpoint).should.eventually.be.rejected;101 });102 });...
proxy-e2e-specs.js
Source:proxy-e2e-specs.js
...22 resBody.status.should.equal(0);23 resBody.value.should.equal(`I'm fine`);24 });25 it('should proxy status as command', async function () {26 const res = await jwproxy.command('/status', 'GET');27 res.should.eql(`I'm fine`);28 });29 describe('new session', function () {30 afterEach(async function () {31 await jwproxy.command('', 'DELETE');32 });33 it('should start a new session', async function () {34 const caps = {browserName: 'fake'};35 const res = await jwproxy.command('/session', 'POST', {desiredCapabilities: caps});36 res.should.have.property('browserName');37 jwproxy.sessionId.should.have.length(48);38 });39 });40 describe('delete session', function () {41 beforeEach(async function () {42 await jwproxy.command('/session', 'POST', {desiredCapabilities: {}});43 });44 it('should quit a session', async function () {45 const res = await jwproxy.command('', 'DELETE');46 should.not.exist(res);47 });48 });...
actions.js
Source:actions.js
1let commands = {}, helpers = {}, extensions = {};2commands.pressKeyCode = async function (keycode, metastate = null, flags = null) {3 return await this.uiautomator2.jwproxy.command('/appium/device/press_keycode', 'POST', {4 keycode,5 metastate,6 flags,7 });8};9commands.longPressKeyCode = async function (keycode, metastate = null, flags = null) {10 return await this.uiautomator2.jwproxy.command('/appium/device/long_press_keycode', 'POST', {11 keycode,12 metastate,13 flags14 });15};16commands.doSwipe = async function (swipeOpts) {17 return await this.uiautomator2.jwproxy.command(`/touch/perform`, 'POST', swipeOpts);18};19commands.doDrag = async function (dragOpts) {20 return await this.uiautomator2.jwproxy.command(`/touch/drag`, 'POST', dragOpts);21};22commands.getOrientation = async function () {23 return await this.uiautomator2.jwproxy.command(`/orientation`, 'GET', {});24};25commands.setOrientation = async function (orientation) {26 orientation = orientation.toUpperCase();27 return await this.uiautomator2.jwproxy.command(`/orientation`, 'POST', {orientation});28};29Object.assign(extensions, commands, helpers);30export { commands, helpers };...
touch.js
Source:touch.js
...6 opts = {7 elementId,8 actions: states9 };10 return await this.uiautomator2.jwproxy.command('/touch/multi/perform', 'POST', opts);11 } else {12 opts = {13 actions: states14 };15 return await this.uiautomator2.jwproxy.command('/touch/multi/perform', 'POST', opts);16 }17};18commands.performActions = async function (actions) {19 log.debug(`Received the following W3C actions: ${JSON.stringify(actions, null, ' ')}`);20 // This is mandatory, since Selenium API uses MOUSE as the default pointer type21 const preprocessedActions = actions22 .map((action) => Object.assign({}, action, action.type === 'pointer' ? {23 parameters: {24 pointerType: 'touch'25 }26 } : {}));27 log.debug(`Preprocessed actions: ${JSON.stringify(preprocessedActions, null, ' ')}`);28 return await this.uiautomator2.jwproxy.command('/actions', 'POST', {actions});29};30Object.assign(extensions, commands);...
Using AI Code Generation
1const { JWProxy } = require('appium-base-driver');2jwproxy.command('/status', 'GET', {}).then((res) => {3 console.log(JSON.stringify(res));4}).catch((err) => {5 console.log(JSON.stringify(err));6});7const { JWProxy } = require('appium-base-driver');8let opts = {9};10jwproxy.proxyReqRes(opts).then((res) => {11 console.log(JSON.stringify(res));12}).catch((err) => {13 console.log(JSON.stringify(err));14});15const { JWProxy } = require('appium-base-driver');16let opts = {17};18jwproxy.proxy(opts).then((res) => {19 console.log(JSON.stringify(res));20}).catch((err) => {21 console.log(JSON.stringify(err));22});
Using AI Code Generation
1jwproxy.command('/wd/hub/session', 'POST', {desiredCapabilities: {browserName: 'chrome'}}).then(function (res) {2 console.log(res);3}).catch(function (err) {4 console.log(err);5});6jwproxy.command('/wd/hub/session', 'POST', {desiredCapabilities: {browserName: 'chrome'}}).then(function (res) {7 console.log(res);8}).catch(function (err) {9 console.log(err);10});11jwproxy.command('/wd/hub/session', 'POST', {desiredCapabilities: {browserName: 'chrome'}}).then(function (res) {12 console.log(res);13}).catch(function (err) {14 console.log(err);15});16jwproxy.command('/wd/hub/session', 'POST', {desiredCapabilities: {browserName: 'chrome'}}).then(function (res) {17 console.log(res);18}).catch(function (err) {19 console.log(err);20});21jwproxy.command('/wd/hub/session', 'POST', {desiredCapabilities: {browserName: 'chrome'}}).then(function (
Using AI Code Generation
1await proxy.command('/session', 'POST', {desiredCapabilities: {browserName: 'chrome'}});2{"sessionId":"b6d4c8f8-0b1c-4f0a-9f8b-5c5e3a3a3f0d","status":13,"value":{"message":"A new session could not be created. (Original error: unknown error: Chrome version must be >= 54.0.2840.0\n (Driver info: chromedriver=2.26.436362 (4e6d1f1a2b6c4d8d8f2e38c1b2e9a9b8f5b5d5b5),platform=Windows NT 10.0.14393 x86_64)"}}3capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, Platform.ANDROID);4capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "6.0");5capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");6capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());7capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.ANDROID_UIAUTOMATOR2);8org.openqa.selenium.SessionNotCreatedException: A new session could not be created. (
Using AI Code Generation
1const { JWProxy } = require('appium-base-driver');2const { server } = require('appium-express');3const { express } = server;4const jwproxy = new JWProxy({server: express, baseurl: '/wd/hub', sessionId: '1234'});5const http = require('http');6const { promisify } = require('util');7const request = promisify(http.request);8const { routeConfiguringFunction } = require('appium-base-driver/lib/protocol/route-config');9const routes = routeConfiguringFunction(jwproxy);10routes.forEach(function(route) {11 express[route.method](route.path, route.handler);12});13(async function() {14 const res = await jwproxy.command('/session/1234/element', 'POST', {using: 'id', value: 'someid'});15 console.log(res);16})();17(async function() {18 const res = await request({19 headers: {20 }21 });22 console.log(res);23})();24This method is not recommended, but it is possible to use the Appium Base Driver directly. You can see an example of this in the [appium-android-driver](
Using AI Code Generation
1const jwproxy = require('./node_modules/appium-base-driver/lib/jsonwp-proxy/proxy');2proxy.command('/wd/hub/session/sessionID/appium/device/lock', 'POST', {seconds: 10}, (err, res) => {3 console.log(res);4});5const jwproxy = require('./node_modules/appium-base-driver/lib/jsonwp-proxy/proxy');6proxy.command('/wd/hub/session/sessionID/appium/device/lock', 'POST', {seconds: 10}, (err, res) => {7 console.log(res);8});9const jwproxy = require('./node_modules/appium-base-driver/lib/jsonwp-proxy/proxy');10proxy.command('/wd/hub/session/sessionID/appium/device/lock', 'POST', {seconds: 10}, (err, res) => {11 console.log(res);12});13const jwproxy = require('./node_modules/appium-base-driver/lib/jsonwp-proxy/proxy');14proxy.command('/wd/hub/session/sessionID/appium/device/lock', 'POST', {seconds: 10}, (err, res) => {15 console.log(res);16});17const jwproxy = require('./node_modules/appium-base-driver/lib/jsonwp-proxy/proxy');18proxy.command('/wd/hub/session/sessionID/appium/device/lock', 'POST', {seconds: 10}, (err, res) => {19 console.log(res);20});21const jwproxy = require('./node_modules/appium-base-driver/lib/jsonwp-proxy/pro
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var _ = require('underscore');4var wd = require('wd');5var chai = require('chai');6var chaiAsPromised = require('chai-as-promised');7var should = chai.should();8var expect = chai.expect;9var Q = require('q');10var logger = require('./logger');11var log = logger.get('appium');12var path = require('path');13var fs = require('fs');14var jwproxy = require('appium-base-driver').jwproxy;15var proxy = new jwproxy({server: 'localhost', port: 4723});16var desired = {17};18var driver = wd.promiseChainRemote('localhost', 4723);19proxy.command('/wd/hub/session', 'POST', desired)20 .then(function (res) {21 return proxy.command('/wd/hub/session/' + res.sessionId + '/element', 'POST', {using: 'id', value: 'hello'});22 })23 .then(function (res) {24 return proxy.command('/wd/hub/session/' + res.sessionId + '/element/' + res.ELEMENT + '/click', 'POST', {});25 })26 .then(function (res) {27 return proxy.command('/wd/hub/session/' + res.sessionId + '/element', 'POST', {using: 'id', value: 'world'});28 })
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!!