Best JavaScript code snippet using appium
editor-page.js
Source:editor-page.js  
...45		position = 1,46		options = { autoscroll: false }47	) {48		const blockLocator = `//*[contains(@${ this.accessibilityIdXPathAttrib }, "${ blockName } Block. Row ${ position }")]`;49		const elements = await this.driver.elementsByXPath( blockLocator );50		const lastElementFound = elements[ elements.length - 1 ];51		if ( elements.length === 0 && options.autoscroll ) {52			const firstBlockVisible = await this.getFirstBlockVisible();53			const lastBlockVisible = await this.getLastBlockVisible();54			// exit if no block is found55			if ( ! firstBlockVisible || ! lastBlockVisible ) {56				return lastElementFound;57			}58			const firstBlockAccessibilityId = await firstBlockVisible.getAttribute(59				this.accessibilityIdKey60			);61			const firstBlockRowMatch = /Row (\d+)\./.exec(62				firstBlockAccessibilityId63			);64			const firstBlockRow =65				firstBlockRowMatch && Number( firstBlockRowMatch[ 1 ] );66			const lastBlockAccessibilityId = await lastBlockVisible.getAttribute(67				this.accessibilityIdKey68			);69			const lastBlockRowMatch = /Row (\d+)\./.exec(70				lastBlockAccessibilityId71			);72			const lastBlockRow =73				lastBlockRowMatch && Number( lastBlockRowMatch[ 1 ] );74			if ( firstBlockRow && position < firstBlockRow ) {75				if ( firstBlockRow === 1 ) {76					// we're at the top already stop recursing77					return lastElementFound;78				}79				// scroll up80				await swipeDown( this.driver );81			} else if ( lastBlockRow && position > lastBlockRow ) {82				// scroll down83				await swipeUp( this.driver );84			}85			return await this.getBlockAtPosition(86				blockName,87				position,88				options89			);90		}91		return lastElementFound;92	}93	async getFirstBlockVisible() {94		const firstBlockLocator = `//*[contains(@${ this.accessibilityIdXPathAttrib }, " Block. Row ")]`;95		const elements = await this.driver.elementsByXPath( firstBlockLocator );96		return elements[ 0 ];97	}98	async getLastBlockVisible() {99		const firstBlockLocator = `//*[contains(@${ this.accessibilityIdXPathAttrib }, " Block. Row ")]`;100		const elements = await this.driver.elementsByXPath( firstBlockLocator );101		return elements[ elements.length - 1 ];102	}103	async hasBlockAtPosition( position = 1, blockName = '' ) {104		return (105			undefined !==106			( await this.getBlockAtPosition( blockName, position ) )107		);108	}109	async addParagraphBlockByTappingEmptyAreaBelowLastBlock() {110		const emptyAreaBelowLastBlock = await this.driver.elementByAccessibilityId(111			'Add paragraph block'112		);113		await emptyAreaBelowLastBlock.click();114	}115	async getTitleElement( options = { autoscroll: false } ) {116		//TODO: Improve the identifier for this element117		const elements = await this.driver.elementsByXPath(118			`//*[contains(@${ this.accessibilityIdXPathAttrib }, "Post title.")]`119		);120		if ( elements.length === 0 && options.autoscroll ) {121			await swipeDown( this.driver );122			return this.getTitleElement( options );123		}124		return elements[ elements.length - 1 ];125	}126	// iOS loads the block list more eagerly compared to Android.127	// This makes this function return elements without scrolling on iOS.128	// So we are keeping this Android only.129	async androidScrollAndReturnElement( accessibilityLabel ) {130		const elements = await this.driver.elementsByXPath(131			`//*[contains(@${ this.accessibilityIdXPathAttrib }, "${ accessibilityLabel }")]`132		);133		if ( elements.length === 0 ) {134			await swipeUp( this.driver, undefined, 100, 1 );135			return this.androidScrollAndReturnElement( accessibilityLabel );136		}137		return elements[ elements.length - 1 ];138	}139	async getLastElementByXPath( accessibilityLabel ) {140		const elements = await this.driver.elementsByXPath(141			`//*[contains(@${ this.accessibilityIdXPathAttrib }, "${ accessibilityLabel }")]`142		);143		return elements[ elements.length - 1 ];144	}145	async getTextViewForHtmlViewContent() {146		const accessibilityId = 'html-view-content';147		let blockLocator = `//*[@${ this.accessibilityIdXPathAttrib }="${ accessibilityId }"]`;148		if ( ! isAndroid() ) {149			blockLocator = `//XCUIElementTypeTextView[starts-with(@${ this.accessibilityIdXPathAttrib }, "${ accessibilityId }")]`;150		}151		return await this.driver.elementByXPath( blockLocator );152	}153	// Returns html content154	// Ensure to take additional steps to handle text being changed by auto correct155	async getHtmlContent() {156		await toggleHtmlMode( this.driver, true );157		const htmlContentView = await this.getTextViewForHtmlViewContent();158		const text = await htmlContentView.text();159		await toggleHtmlMode( this.driver, false );160		return text;161	}162	// set html editor content explicitly163	async setHtmlContent( html ) {164		await toggleHtmlMode( this.driver, true );165		const base64String = Buffer.from( html ).toString( 'base64' );166		await this.driver.setClipboard( base64String, 'plaintext' );167		const htmlContentView = await this.getTextViewForHtmlViewContent();168		if ( isAndroid() ) {169			// Attention! On Android `.type()` replaces the content of htmlContentView instead of appending170			// contrary to what iOS is doing. On Android tried calling `driver.pressKeycode( 279 ) // KEYCODE_PASTE`171			// before to paste, but for some reason it didn't work on GitHub Actions but worked only on Sauce Labs172			await htmlContentView.type( html );173		} else {174			await htmlContentView.click();175			await doubleTap( this.driver, htmlContentView );176			// Sometimes double tap is not enough for paste menu to appear, so we also long press177			await longPressMiddleOfElement( this.driver, htmlContentView );178			const pasteButton = this.driver.elementByXPath(179				'//XCUIElementTypeMenuItem[@name="Paste"]'180			);181			await pasteButton.click();182			await this.driver.sleep( 3000 ); // wait for paste notification to disappear183		}184		await toggleHtmlMode( this.driver, false );185	}186	async dismissKeyboard() {187		await this.driver.sleep( 1000 ); /// wait for any keyboard animations188		const keyboardShown = await this.driver.isKeyboardShown();189		if ( ! keyboardShown ) {190			return;191		}192		if ( isAndroid() ) {193			return await this.driver.hideDeviceKeyboard();194		}195		const hideKeyboardToolbarButton = await this.driver.elementByXPath(196			'//XCUIElementTypeButton[@name="Hide keyboard"]'197		);198		await hideKeyboardToolbarButton.click();199	}200	async dismissAndroidClipboardSmartSuggestion() {201		if ( ! isAndroid() ) {202			return;203		}204		const dismissClipboardSmartSuggestionLocator = `//*[@${ this.accessibilityIdXPathAttrib }="Dismiss Smart Suggestion"]`;205		const smartSuggestions = await this.driver.elementsByXPath(206			dismissClipboardSmartSuggestionLocator207		);208		if ( smartSuggestions.length !== 0 ) {209			smartSuggestions[ 0 ].click();210		}211	}212	async openBlockSettings( block ) {213		await block.click();214		const settingsButton = await block.elementByAccessibilityId(215			'Open Settings'216		);217		await settingsButton.click();218	}219	async dismissBottomSheet() {220		return await swipeDown( this.driver );221	}222	// =========================223	// Block toolbar functions224	// =========================225	async addNewBlock( blockName, relativePosition ) {226		// Click add button227		let identifier = 'Add block';228		if ( isAndroid() ) {229			identifier = 'Add block, Double tap to add a block';230		}231		const addButton = await this.driver.elementByAccessibilityId(232			identifier233		);234		if ( relativePosition === 'before' ) {235			await longPressMiddleOfElement( this.driver, addButton );236			const addBlockBeforeButton = await this.driver.elementByAccessibilityId(237				'Add Block Before'238			);239			await addBlockBeforeButton.click();240		} else {241			await addButton.click();242		}243		// Click on block of choice244		const blockButton = await this.findBlockButton( blockName );245		if ( isAndroid() ) {246			await blockButton.click();247		} else {248			await this.driver.execute( 'mobile: tap', {249				element: blockButton,250				x: 10,251				y: 10,252			} );253		}254	}255	static getInserterPageHeight( screenHeight ) {256		// Rough estimate of a swipe distance required to scroll one page of blocks257		return screenHeight * 0.82;258	}259	// Attempts to find the given block button in the block inserter control.260	async findBlockButton( blockName ) {261		const blockAccessibilityLabel = `${ blockName } block`;262		const blockAccessibilityLabelNewBlock = `${ blockAccessibilityLabel }, newly available`;263		if ( isAndroid() ) {264			const size = await this.driver.getWindowSize();265			const x = size.width / 2;266			// Checks if the Block Button is available, and if not will scroll to the second half of the available buttons.267			while (268				! ( await this.driver.hasElementByAccessibilityId(269					blockAccessibilityLabel270				) ) &&271				! ( await this.driver.hasElementByAccessibilityId(272					blockAccessibilityLabelNewBlock273				) )274			) {275				swipeFromTo(276					this.driver,277					{ x, y: size.height - 100 },278					{ x, y: EditorPage.getInserterPageHeight( size.height ) }279				);280			}281			if (282				await this.driver.hasElementByAccessibilityId(283					blockAccessibilityLabelNewBlock284				)285			) {286				return await this.driver.elementByAccessibilityId(287					blockAccessibilityLabelNewBlock288				);289			}290			return await this.driver.elementByAccessibilityId(291				blockAccessibilityLabel292			);293		}294		const blockButton = ( await this.driver.hasElementByAccessibilityId(295			blockAccessibilityLabelNewBlock296		) )297			? await this.driver.elementByAccessibilityId(298					blockAccessibilityLabelNewBlock299			  )300			: await this.driver.elementByAccessibilityId(301					blockAccessibilityLabel302			  );303		const size = await this.driver.getWindowSize();304		// The virtual home button covers the bottom 34 in portrait and 21 on landscape on iOS.305		// We start dragging a bit above it to not trigger home button.306		const height = size.height - 50;307		while ( ! ( await blockButton.isDisplayed() ) ) {308			await this.driver.execute( 'mobile: dragFromToForDuration', {309				fromX: 50,310				fromY: height,311				toX: 50,312				toY: EditorPage.getInserterPageHeight( height ),313				duration: 0.5,314			} );315		}316		return blockButton;317	}318	async clickToolBarButton( buttonName ) {319		const toolBarButton = await this.driver.elementByAccessibilityId(320			buttonName321		);322		await toolBarButton.click();323	}324	// =========================325	// Inline toolbar functions326	// =========================327	// position of the block to move up328	async moveBlockUpAtPosition( position, blockName = '' ) {329		if ( ! ( await this.hasBlockAtPosition( position, blockName ) ) ) {330			throw Error( `No Block at position ${ position }` );331		}332		const parentLocator = `//*[@${ this.accessibilityIdXPathAttrib }="${ blockName } Block. Row ${ position }."]`;333		let blockLocator = `${ parentLocator }/following-sibling::*`;334		blockLocator += isAndroid() ? '' : '//*';335		blockLocator += `[@${336			this.accessibilityIdXPathAttrib337		}="Move block up from row ${ position } to row ${ position - 1 }"]`;338		const moveUpButton = await this.driver.elementByXPath( blockLocator );339		await moveUpButton.click();340	}341	// position of the block to move down342	async moveBlockDownAtPosition( position, blockName = '' ) {343		if ( ! ( await this.hasBlockAtPosition( position, blockName ) ) ) {344			throw Error( `No Block at position ${ position }` );345		}346		const parentLocator = `//*[contains(@${ this.accessibilityIdXPathAttrib }, "${ blockName } Block. Row ${ position }.")]`;347		let blockLocator = `${ parentLocator }/following-sibling::*`;348		blockLocator += isAndroid() ? '' : '//*';349		blockLocator += `[@${350			this.accessibilityIdXPathAttrib351		}="Move block down from row ${ position } to row ${ position + 1 }"]`;352		const moveDownButton = await this.driver.elementByXPath( blockLocator );353		await moveDownButton.click();354	}355	// position of the block to remove356	// Block will no longer be present if this succeeds357	async removeBlockAtPosition( blockName = '', position = 1 ) {358		if ( ! ( await this.hasBlockAtPosition( position, blockName ) ) ) {359			throw Error( `No Block at position ${ position }` );360		}361		const buttonElementName = isAndroid()362			? '//*'363			: '//XCUIElementTypeButton';364		const blockActionsMenuButtonIdentifier = `Open Block Actions Menu`;365		const blockActionsMenuButtonLocator = `${ buttonElementName }[contains(@${ this.accessibilityIdXPathAttrib }, "${ blockActionsMenuButtonIdentifier }")]`;366		if ( isAndroid() ) {367			const block = await this.getBlockAtPosition( blockName, position );368			let checkList = await this.driver.elementsByXPath(369				blockActionsMenuButtonLocator370			);371			while ( checkList.length === 0 ) {372				await swipeUp( this.driver, block ); // Swipe up to show remove icon at the bottom373				checkList = await this.driver.elementsByXPath(374					blockActionsMenuButtonLocator375				);376			}377		}378		const blockActionsMenuButton = await this.driver.elementByXPath(379			blockActionsMenuButtonLocator380		);381		await blockActionsMenuButton.click();382		const removeActionButtonIdentifier = 'Remove block';383		const removeActionButtonLocator = `${ buttonElementName }[contains(@${ this.accessibilityIdXPathAttrib }, "${ removeActionButtonIdentifier }")]`;384		const removeActionButton = await this.driver.elementByXPath(385			removeActionButtonLocator386		);387		await removeActionButton.click();...mainPage.js
Source:mainPage.js  
1/*************************************************************************2 *3 * REV SOFTWARE CONFIDENTIAL4 *5 * [2013] - [2017] Rev Software, Inc.6 * All Rights Reserved.7 *8 * NOTICE:  All information contained herein is, and remains9 * the property of Rev Software, Inc. and its suppliers,10 * if any.  The intellectual and technical concepts contained11 * herein are proprietary to Rev Software, Inc.12 * and its suppliers and may be covered by U.S. and Foreign Patents,13 * patents in process, and are protected by trade secret or copyright law.14 * Dissemination of this information or reproduction of this material15 * is strictly forbidden unless prior written permission is obtained16 * from Rev Software, Inc.17 */18var App = {19    dropdown: {20        methods: 'com.nuubit.tester:id/spMethod',21        operationModes: 'com.nuubit.tester:id/spMode'22    },23    list: {24        methods: {25            GET: "//android.widget.TextView[@index='0']",26            POST: "//android.widget.TextView[@index='1']",27            PUT: "//android.widget.TextView[@index='2']",28            DELETE: "//android.widget.TextView[@index='3']",29            HEAD: "//android.widget.TextView[@index='4']",30            CONNECT: "//android.widget.TextView[@index='5']",31            OPTIONS: "//android.widget.TextView[@index='6']",32            TRACE: "//android.widget.TextView[@index='7']"33        },34        operationModes: {35            transfer_and_report: "//android.widget.TextView[@index='0']",36            transfer_only: "//android.widget.TextView[@index='1']",37            report_only: "//android.widget.TextView[@index='2']",38            off: "//android.widget.TextView[@index='3']"39        },40        config: '//android.widget.TextView',41        stats: '//android.widget.TextView'42    },43    input: {44        url: 'com.nuubit.tester:id/tlQuery'45    },46    button: {47        send: 'com.nuubit.tester:id/rlRun'48    },49    output: {50        response: 'com.nuubit.tester:id/tvMain',51        responseHeaders: 'com.nuubit.tester:id/tvHeaders'52    },53    menuBtn: {54        button: 'android.widget.ImageView'55    },56    menuOptions: {57        configurationView: '//android.widget.TextView[@text=\'Configuration view\']',58        statsView: '//android.widget.TextView[@text=\'Statistic view\']'59    },60    getConfigurationPage: function (driver) {61        return driver62            .elementByClassName(App.menuBtn.button)63            .click()64            .elementByXPath(App.menuOptions.configurationView)65            .click();66    },67    getConfigurationList: function (driver) {68        return driver69            .elementsByXPath(App.list.config);70    },71    getStatsReportingInterval: function (driver) {72        return driver73            .elementsByXPath(App.list.config)74            .at(2);75    },76    getOperationMode: function (driver) {77        return driver78            .elementsByXPath(App.list.config)79            .at(28);80    },81    getConfigVariables: function (driver) {82        var configVariables = [];83        return driver84            .elementsByXPath(App.list.config)85            .then(function (configList) {86                configVariables[0] = configList[1].text();87                configVariables[1] = configList[3].text();88                configVariables[2] = configList[5].text();89                configVariables[3] = configList[7].text();90                configVariables[4] = configList[9].text();91                configVariables[5] = configList[11].text();92                configVariables[6] = configList[13].text();93                configVariables[7] = configList[15].text();94                configVariables[8] = configList[17].text();95                configVariables[9] = configList[19].text();96                return configVariables;97            });98    },99    getConfigValues: function (driver) {100        var configValues = [];101        return driver102            .elementsByXPath(App.list.config)103            .then(function (configList) {104                configValues[0] = configList[2].text();105                configValues[1] = configList[4].text();106                configValues[2] = configList[6].text();107                configValues[3] = configList[8].text();108                configValues[4] = configList[10].text();109                configValues[5] = configList[12].text();110                configValues[6] = configList[14].text();111                configValues[7] = configList[16].text();112                configValues[8] = configList[18].text();113                configValues[9] = configList[20].text();114                return configValues;115            });116    },117    clickMenuButton: function (driver) {118        return driver119            .elementByClassName(App.menuBtn.button)120            .click();121    },122    clickConfigViewButton: function (driver) {123        return driver124            .elementByXPath(App.menuOptions.configurationView)125            .click();126    },127    clickStatsViewButton: function (driver) {128        return driver129            .elementByXPath(App.menuOptions.statsView)130            .click();131    },132    getStatsValueRequests: function (driver) {133        var actions = require("./../../helpers/actions");134        var wd = require("wd");135        wd.addPromiseChainMethod('scrollDown', actions.scrollDown);136        var revRequests = undefined;137        return driver138            .sleep(2000)139            .scrollDown()140            .scrollDown()141            .scrollDown()142            .scrollDown()143            .scrollDown()144            .scrollDown()145            .sleep(5000)146            .elementsByXPath(App.list.stats)147            .then(function (statsList) {148                revRequests = statsList[21].text();149                return revRequests;150            });151    },152    setModeReportOnly: function (driver) {153       return driver154            .elementById(App.dropdown.operationModes)155            .click()156            .elementByXPath(App.list.operationModes.report_only)157            .click();158    },159    setModeOff: function (driver) {160        return driver161            .elementById(App.dropdown.operationModes)162            .click()163            .elementByXPath(App.list.operationModes.off)164            .click();165    },166    setModeTransferOnly: function (driver) {167        return driver168            .elementById(App.dropdown.operationModes)169            .click()170            .elementByXPath(App.list.operationModes.transfer_only)171            .click();172    },173    setModeTransferAndReport: function (driver) {174        return driver175            .elementById(App.dropdown.operationModes)176            .click()177            .elementByXPath(App.list.operationModes.transfer_and_report)178            .click();179    },180    getInputUrl: function (driver) {181        return driver182            .elementById(App.input.url);183    },184    clickSendBtn: function (driver) {185        return driver186            .elementById(App.button.send)187            .click();188    },189    getResponseHeaders: function (driver) {190        return driver191            .elementById(App.output.responseHeaders);192    },193    getResponseBody: function (driver) {194        return driver195            .elementById(App.output.response);196    },197    setHttpMethodGET: function (driver) {198        return driver199            .elementById(App.dropdown.methods)200            .click()201            .elementByXPath(App.list.methods.GET)202            .click();203    },204    setHttpMethodPOST: function (driver) {205        return driver206            .elementById(App.dropdown.methods)207            .click()208            .elementByXPath(App.list.methods.POST)209            .click();210    },211    setHttpMethodPUT: function (driver) {212        return driver213            .elementById(App.dropdown.methods)214            .click()215            .elementByXPath(App.list.methods.PUT)216            .click();217    },218    setHttpMethodDELETE: function (driver) {219        return driver220            .elementById(App.dropdown.methods)221            .click()222            .elementByXPath(App.list.methods.DELETE)223            .click();224    },225    setHttpMethodCONNECT: function (driver) {226        return driver227            .elementById(App.dropdown.methods)228            .click()229            .elementByXPath(App.list.methods.CONNECT)230            .click();231    },232    setHttpMethodHEAD: function (driver) {233        return driver234            .elementById(App.dropdown.methods)235            .click()236            .elementByXPath(App.list.methods.HEAD)237            .click();238    },239    setHttpMethodOPTIONS: function (driver) {240        return driver241            .elementById(App.dropdown.methods)242            .click()243            .elementByXPath(App.list.methods.OPTIONS)244            .click();245    },246    setHttpMethodTRACE: function (driver) {247        return driver248            .elementById(App.dropdown.methods)249            .click()250            .elementByXPath(App.list.methods.TRACE)251            .click();252    }253};...find-by-xpath-specs.js
Source:find-by-xpath-specs.js  
1"use strict";2var setup = require("../../common/setup-base")3  , desired = require('././desired')4  , Q = require("q")5  , _ = require("underscore")6  , spinWait = require("../../../helpers/spin.js").spinWait;7describe('uicatalog - find by xpath @skip-ios6', function () {8  var driver;9  setup(this, desired).then(function (d) { driver = d; });10  describe('individual calls', function () {11    var setupXpath = function (driver) {12      return driver.elementByXPath("//UIAStaticText[contains(@label,'Buttons')]")13        .click();14    };15    afterEach(function (done) {16      driver17        .elementByName('UICatalog').click()18        .sleep(1000)19        .nodeify(done);20    });21    it('should return the last button', function (done) {22      driver23        .resolve(setupXpath(driver))24        .elementByXPath("//UIAButton[last()]").text()25          .should.become("Button") // this is the name of the last button26        .nodeify(done);27    });28    it('should return a single element', function (done) {29      driver30        .resolve(setupXpath(driver))31        .elementByXPath("//UIAButton").text()32          .should.become("UICatalog")33        .nodeify(done);34    });35    it('should return multiple elements', function (done) {36      driver37        .resolve(setupXpath(driver))38        .elementsByXPath("//UIAButton")39          .should.eventually.have.length.above(5)40        .nodeify(done);41    });42    it('should filter by name', function (done) {43      driver44        .resolve(setupXpath(driver))45        .elementByXPath("//UIAButton[@name='X Button']").text()46          .should.become("X Button")47        .nodeify(done);48    });49    it('should know how to restrict root-level elements', function (done) {50      driver51        .resolve(setupXpath(driver))52        .elementByXPath("/UIAButton")53          .should.be.rejectedWith(/status: 7/)54        .nodeify(done);55    });56    it('should search an extended path by child', function (done) {57      driver58        .resolve(setupXpath(driver))59        .then(function () {60          return spinWait(function () {61            return driver.elementByXPath("//UIANavigationBar/UIAStaticText")62              .text().should.become('Buttons');63          });64        }).nodeify(done);65    });66    it('should search an extended path by descendant', function (done) {67      driver68        .resolve(setupXpath(driver))69        .elementsByXPath("//UIATableCell//UIAButton").then(function (els) {70          return Q.all(_(els).map(function (el) { return el.text(); }));71        }).then(function (texts) {72          texts.should.not.include("UICatalog");73          texts.should.include("X Button");74        }).nodeify(done);75    });76    it('should filter by indices', function (done) {77      driver78        .resolve(setupXpath(driver))79        .elementByXPath("//UIATableCell[4]/UIAButton[1]")80        .getAttribute('name').should.become("X Button")81        .nodeify(done);82    });83    it('should filter by partial text', function (done) {84      driver85        .resolve(setupXpath(driver))86        .elementByXPath("//UIATableCell//UIAButton[contains(@name, 'X ')]").text()87          .should.become("X Button")88        .nodeify(done);89    });90    describe('duplicate text field', function () {91      it('should find only one text field', function (done) {92        driver93          .waitForElementByName('*Text Fields*', 3000, 500).click()94          .sleep(2000)95          .elementsByXPath('//UIATableView["Empty list"]/UIATableCell[1]/UIATextField')96            .should.eventually.have.length(1)97          .nodeify(done);98      });99      it('should find only one text field when doing relative search', function (done) {100        driver101          .waitForElementByName('*Text Fields*', 3000, 500).click()102          .sleep(2000)103          .elementsByXPath('//UIATableView["Empty list"]')104          .elementsByXPath('>', '//UIATableCell[1]/UIATextField')105            .should.eventually.have.length(1)106          .nodeify(done);107      });108      it('should find only one secure text field', function (done) {109        driver110          .waitForElementByName('*Text Fields*', 3000, 500).click()111          .sleep(2000)112          .elementsByXPath('//UIATableView["Empty list"]/UIATableCell[3]/UIASecureTextField')113            .should.eventually.have.length(1)114          .nodeify(done);115      });116    });117  });118  describe('multiple calls', function () {119    var runs = 5;120    var test = function (path, minLength) {121      return function () {122        it('should not crash', function (done) {123          driver124            .elementsByXPath(path)125              .should.eventually.have.length.above(minLength)126            .nodeify(done);127        });128      };129    };130    describe('finding specific path', function () {131      for (var n = 0; n < runs; n++) {132        describe('test ' + (n + 1), test("//UIAApplication[1]/UIAWindow/UIATableView/UIATableCell", 17));133      }134    });135    describe('finding //*', function () {136      for (var n = 0; n < runs; n++) {137        describe('test ' + (n + 1), test("//*", 52));138      }139    });140  });...find-element-tests.js
Source:find-element-tests.js  
...19      await driver.elementByXPath('//dontexist')20              .should.eventually.be.rejectedWith(/7/);21    });22    it('should find multiple elements', async function () {23      let els = await driver.elementsByXPath('//MockListItem');24      els.should.have.length(3);25    });26    it('should not find multiple elements that are not there', async function () {27      let els = await driver.elementsByXPath('//dontexist');28      els.should.eql([]);29    });30    it('should find a single element by id', async function () {31      let el = await driver.elementById('wv');32      should.exist(el.value);33    });34    it('should not find a single element by id that is not there', async function () {35      await driver.elementById('dontexist')36              .should.eventually.be.rejectedWith(/7/);37    });38    it('should find multiple elements by id', async function () {39      let els = await driver.elementsById('li');40      els.should.have.length(2);41    });42    it('should not find multiple elements by id that are not there', async function () {43      let els = await driver.elementsById('dontexist');44      els.should.eql([]);45    });46    it('should find a single element by class', async function () {47      let el = await driver.elementByClassName('MockWebView');48      should.exist(el.value);49    });50    it('should not find a single element by class that is not there', async function () {51      await driver.elementById('dontexist')52              .should.eventually.be.rejectedWith(/7/);53    });54    it('should find multiple elements by class', async function () {55      let els = await driver.elementsByClassName('MockListItem');56      els.should.have.length(3);57    });58    it('should not find multiple elements by class that are not there', async function () {59      let els = await driver.elementsByClassName('dontexist');60      els.should.eql([]);61    });62    it('should not find a single element with bad strategy', async function () {63      await driver.elementByCss('.sorry')64              .should.eventually.be.rejectedWith(/9/);65    });66    it('should not find a single element with bad selector', async function () {67      await driver.elementByXPath('badsel')68              .should.eventually.be.rejectedWith(/32/);69    });70    it('should not find multiple elements with bad strategy', async function () {71      await driver.elementsByCss('.sorry')72              .should.eventually.be.rejectedWith(/9/);73    });74    it('should not find multiple elements with bad selector', async function () {75      await driver.elementsByXPath('badsel')76              .should.eventually.be.rejectedWith(/32/);77    });78    it('should find an element from another element', async function () {79      let el = await driver.elementById('iframe1');80      let title = await el.elementByTagName('title');81      let earlierTitle = await driver.elementByTagName('title');82      (await earlierTitle.equals(title)).should.equal(false);83    });84    it('should find multiple elements from another element', async function () {85      let el = await driver.elementByTagName('html');86      let titles = await el.elementsByTagName('title');87      titles.length.should.equal(2);88    });89    it('should not find an element that doesnt exist from another element', async function () {...by-xpath-e2e-specs.js
Source:by-xpath-e2e-specs.js  
...23    let el = await driver.elementByXPath(`//${atv}[@text='Accessibility']`);24    await el.text().should.eventually.equal('Accessibility');25  });26  it('should find element by attribute', async function () {27    await driver.elementsByXPath(`//*[@enabled='true' and @focused='true']`)28      .should.eventually.have.length(1);29  });30  it('should find exactly one element via elementsByXPath', async function () {31    let els = await driver.elementsByXPath(`//${atv}[@text='Accessibility']`);32    els.length.should.equal(1);33    await els[0].text().should.eventually.equal('Accessibility');34  });35  it('should find element by partial text', async function () {36    let el = await driver.elementByXPath(`//${atv}[contains(@text, 'Accessibility')]`);37    await el.text().should.eventually.equal('Accessibility');38  });39  it('should find the last element', async function () {40    let el = await driver.elementByXPath(`(//${atv})[last()]`);41    let text = await el.text();42    ["OS", "Text", "Views", "Preference"].should.include(text);43  });44  it('should find element by index and embedded desc', async function () {45    let el = await driver.elementByXPath(`//${f}//${atv}[5]`);46    await el.text().should.eventually.equal('Content');47  });48  it('should find all elements', async function () {49    let els = await driver.elementsByXPath(`//*`);50    els.length.should.be.above(2);51  });52  it('should find the first element when searching for all elements', async function () {53    let el = await driver.elementByXPath(`//*`);54    el.should.exist;55  });56  it('should find less elements with compression turned on', async function () {57    await driver.updateSettings({"ignoreUnimportantViews": false});58    let elementsWithoutCompression = await driver.elementsByXPath(`//*`);59    await driver.updateSettings({"ignoreUnimportantViews": true});60    let elementsWithCompression = await driver.elementsByXPath(`//*`);61    elementsWithoutCompression.length.should.be.greaterThan(elementsWithCompression.length);62  });63  it('should find toast message element by text @skip-ci', async function () {64    // skip on travis, as it is too slow and the message is removed before65    // we can find it66    if (process.env.TESTOBJECT_E2E_TESTS) {67      this.skip();68    }69    await driver.startActivity({appPackage: 'io.appium.android.apis', appActivity: '.view.PopupMenu1'});70    await driver.waitForElementByAccessibilityId('Make a Popup!');71    let popUpEl = await driver.elementByAccessibilityId('Make a Popup!');72    await popUpEl.click();73    await driver.waitForElementByXPath(`.//*[@text='Search']`);74    let searchEl = await driver.elementByXPath(`.//*[@text='Search']`);...by-xpath-specs.js
Source:by-xpath-specs.js  
1"use strict";2var setup = require("../../../common/setup-base")3  , desired = require("../desired")4  , atv = 'android.widget.TextView'5  , alv = 'android.widget.ListView'6  ;7describe("apidemo - find - by xpath", function () {8  var driver;9  setup(this, desired).then(function (d) { driver = d; });10  var f = "android.widget.FrameLayout";11  var l = alv;12  var t = atv;13  before(function (done) {14    driver.sleep(2000).nodeify(done);15  });16  it('should throw with status 7 when matching nothing', function (done) {17    driver18      .elementByXPath('//whatthat')19      .should.be.rejectedWith(/status: 7/)20      .nodeify(done);21  });22  it('should throw with status 7 for hierarchy root', function (done) {23    driver24      .elementByXPath('/*')25      .should.be.rejectedWith(/status: 7/)26      .nodeify(done);27  });28  it('should find element by type', function (done) {29    driver30      .elementByXPath('//' + t).text()31        .should.become("API Demos")32      .nodeify(done);33  });34  it('should find element by text', function (done) {35    driver36      .elementByXPath("//" + t + "[@text='Accessibility']").text()37        .should.become("Accessibility")38      .nodeify(done);39  });40  // This test verifies a specific XPath issue has been resolved.41  // https://github.com/appium/appium/pull/373042  it('should find exactly one element via elementsByXPath', function (done) {43    driver44      .elementsByXPath("//" + t + "[@text='Accessibility']").then(function (els) {45        els.length.should.equal(1);46        els[0].text().should.become("Accessibility");47      })48      .nodeify(done);49  });50  it('should find element by partial text', function (done) {51    driver52      .elementByXPath("//" + t + "[contains(@text, 'Accessibility')]").text()53        .should.become("Accessibility")54      .nodeify(done);55  });56  it('should find the last element', function (done) {57    driver58      .elementByXPath("(//" + t + ")[last()]").text()59      .then(function (text) {60        ["OS", "Text", "Views", "Preference"].should.include(text);61      }).nodeify(done);62  });63  it('should find element by xpath index and child @skip-ci', function (done) {64    driver65      .elementByXPath("//" + f + "[2]/" + l + "[1]/" + t + "[4]").text()66        .should.become("App")67      .nodeify(done);68  });69  it('should find element by index and embedded desc', function (done) {70    driver71      .elementByXPath("//" + f + "//" + t + "[5]").text()72        .should.become("Content")73      .nodeify(done);74  });75  it('should find all elements', function (done) {76    driver77      .elementsByXPath("//*").then(function (els) {78        els.length.should.be.above(2);79      })80      .nodeify(done);81  });82  it('should find the first element when searching for all elements', function (done) {83    driver84      .elementByXPath("//*").then(function (el) {85        return el.should.be.ok;86      })87      .nodeify(done);88  });89  it('should find less elements with compression turned on', function (done) {90    var getElementsWithoutCompression = function () {91      return driver.updateSettings({"ignoreUnimportantViews": false}).elementsByXPath("//*");92    };93    var getElementsWithCompression    = function () {94      return driver.updateSettings({"ignoreUnimportantViews": true }).elementsByXPath("//*");95    };96    var elementsWithoutCompression, elementsWithCompression;97    getElementsWithoutCompression()98    .then(function (els) {99      elementsWithoutCompression = els;100      return getElementsWithCompression();101    })102    .then(function (els) {103      elementsWithCompression = els;104    })105    .then(function () {106      return elementsWithoutCompression.length.should.be.greaterThan(elementsWithCompression.length);107    })108    .nodeify(done);109  });...openDrawerPage.js
Source:openDrawerPage.js  
1/*************************************************************************2 *3 * REV SOFTWARE CONFIDENTIAL4 *5 * [2013] - [2017] Rev Software, Inc.6 * All Rights Reserved.7 *8 * NOTICE:  All information contained herein is, and remains9 * the property of Rev Software, Inc. and its suppliers,10 * if any.  The intellectual and technical concepts contained11 * herein are proprietary to Rev Software, Inc.12 * and its suppliers and may be covered by U.S. and Foreign Patents,13 * patents in process, and are protected by trade secret or copyright law.14 * Dissemination of this information or reproduction of this material15 * is strictly forbidden unless prior written permission is obtained16 * from Rev Software, Inc.17 */18"use strict";19var wd = require("wd"),20    config = require("config"),21    actions = require("./../../helpers/actions"),22    Waits = require("./../../page_objects/RevTester/waits"),23    Functions = require("./functions");24var defaultStatsVars = config.get('defaultStatsVars');25wd.addPromiseChainMethod('scrollDown', actions.scrollDown);26wd.addPromiseChainMethod('waitForResponse', Waits.waitForResponse);27var Counters = {28    list: {29        drawer: '//android.widget.TextView'30    },31    getOriginRequests: function (driver) {32        return driver33            .waitForResponse(driver)34            .elementsByXPath(Counters.list.drawer)35            .then(function (countersList) {36                return countersList[47].text().then(function (value) {37                    return value === 'originRequests' ? countersList[48].text() : countersList[47].text();38                });39            });40    },41    getRevRequests: function (driver) {42        return driver43            .waitForResponse(driver)44            .elementsByXPath(Counters.list.drawer)45            .then(function (countersList) {46                return countersList[45].text().then(function (value) {47                    return value === 'revRequests' ? countersList[46].text() : countersList[45].text();48                });49            });50    },51    getCounterRequestCount: function (driver) {52        return driver53            .waitForResponse(driver)54            .elementsByXPath(Counters.list.drawer)55            .then(function (countersList) {56                return countersList[62].text().then(function (value) {57                    return value === 'Request count' ? countersList[63].text() : countersList[62].text();58                });59            });60    },61    getTotalStatsRequestUploaded: function (driver) {62        return driver63            .waitForResponse(driver)64            .elementsByXPath(Counters.list.drawer)65            .then(function (countersList) {66                return countersList[58].text();67            });68    },69    // Function getCounterTotalRequestsStandard scrolls down the counters and returns value of the totalRequestsStandard70    getCounterTotalRequestsStandard: function (driver) {71        var totalRequestsStandard = undefined;72        return driver73            .waitForResponse(driver)74            .scrollDown()75            .scrollDown()76            .scrollDown()77            .elementsByXPath(Counters.list.drawer)78            .then(function (countersList) {79                totalRequestsStandard = countersList[52].text();80                return totalRequestsStandard;81            });82    }83};...find-system-ui-el-e2e-specs.js
Source:find-system-ui-el-e2e-specs.js  
...23      await driver.quit();24    }25  });26  it('should not find statusBarBackground element via xpath', async function () {27    let statusBar = await driver.elementsByXPath(`//*[@resource-id='android:id/statusBarBackground']`); //check server (NPE) if allowInvisibleElements is unset on server side28    statusBar.length.should.be.equal(0);29    await driver.updateSettings({"allowInvisibleElements": false});30    let statusBarWithInvisibleEl = await driver.elementsByXPath(`//*[@resource-id='android:id/statusBarBackground']`);31    statusBarWithInvisibleEl.length.should.be.equal(0);32  });33  it('should find statusBarBackground element via xpath', async function () {34    await driver.updateSettings({"allowInvisibleElements": true});35    await driver.elementByXPath(`//*[@resource-id='android:id/statusBarBackground']`).should.eventually.exist;36  });...Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder().forBrowser('chrome').build();3driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');4driver.findElement(webdriver.By.name('btnG')).click();5driver.wait(function() {6  return driver.getTitle().then(function(title) {7    return title === 'webdriver - Google Search';8  });9}, 1000);10var webdriver = require('selenium-webdriver');11var driver = new webdriver.Builder().forBrowser('chrome').build();12driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');13driver.findElement(webdriver.By.name('btnG')).click();14driver.wait(function() {15  return driver.getTitle().then(function(title) {16    return title === 'webdriver - Google Search';17  });18}, 1000);19var webdriver = require('selenium-webdriver');20var driver = new webdriver.Builder().forBrowser('chrome').build();21driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');22driver.findElement(webdriver.By.name('btnG')).click();23driver.wait(function() {24  return driver.getTitle().then(function(title) {25    return title === 'webdriver - Google Search';26  });27}, 1000);28var webdriver = require('selenium-webdriver');29var driver = new webdriver.Builder().forBrowser('chrome').build();30driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');31driver.findElement(webdriver.By.name('btnG')).click();32driver.wait(function() {33  return driver.getTitle().then(function(title) {34    return title === 'webdriver - Google Search';35  });36}, 1000);37var webdriver = require('selenium-webdriver');38var driver = new webdriver.Builder().forBrowser('chrome').build();39driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');Using AI Code Generation
1var webdriver = require('webdriverio');2var options = { desiredCapabilities: { browserName: 'chrome' } };3var client = webdriver.remote(options);4  .init()5  .title(function(err, res) {6    console.log('Title was: ' + res.value);7  })8  .end();Using AI Code Generation
1var webdriver = require('wd');2var assert = require('assert');3var desired = {4};5var browser = webdriver.remote('localhost', 4723);6browser.init(desired, function() {7    console.log(el.length);8    browser.quit();9  });10});11info: [debug] Responding to client with success: {"status":0,"value":[{"ELEMENT":"1"},{"ELEMENT":"2"},{"ELEMENT":"3"},{"ELEMENT":"4"},{"ELEMENT":"5"},{"ELEMENT":"6"},{"ELEMENT":"7"},{"ELEMENT":"8"},{"ELEMENT":"9"},{"ELEMENT":"10"},{"ELEMENT":"11"},{"ELEMENT":"12"},{"ELEMENT":"13"},{"ELEMENT":"14"},{"ELEMENT":"15"},{"ELEMENT":"16"},{"ELEMENT":"17"},{"ELEMENT":"18"},{"ELEMENT":"19"},{"ELEMENT":"20"},{"ELEMENT":"21"},{"ELEMENT":"22"},{"ELEMENT":"23"},{"ELEMENT":"24"},{"ELEMENT":"25"},{"ELEMENT":"26"},{"ELEMENT":"27"},{"ELEMENT":"28"},{"ELEMENT":"29"},{"ELEMENT":"30"},{"ELEMENT":"31"},{"ELEMENT":"32"},{"ELEMENT":"33"},{"ELEMENT":"34"},{"ELEMENT":"35"},{"ELEMENT":"36"},{"ELEMENT":"37"},{"ELEMENT":"38"},{"ELEMENT":"39"},{"ELEMENT":"40"},{"ELEMENT":"41"},{"ELEMENT":"42"},{"ELEMENT":"43"},{"ELEMENT":"44"},{"ELEMENT":"45"},{"ELEMENT":"46"},{"ELEMENT":"47"},{"ELEMENT":"48"},{"ELEMENT":"49"},{"ELEMENT":"50"},{"ELEMENT":"51"},{"ELEMENT":"52"},{"ELEMENT":"53"},{"ELEMENT":"54"},{"ELEMENT":"55"},{"ELEMENT":"56"},{"ELEMENT":"57"},{"ELEMENT":"58"},{"ELEMENT":"59"},{"ELEMENT":"60"},{"ELEMENT":"61"},{"ELEMENT":"62"},{"ELEMENT":"63"},{"ELEMENT":"64"},{"ELEMENT":"65"},{"ELEMENT":"66"},{"ELEMENT":"67"},{"ELEMENT":"68"},{"ELEMENT":"69"},{"ELEMENT":"70"},{"ELEMENT":"71"},{"ELEMENT":"72"},{"ELEMENT":"73"},{"ELEMENT":"74"},{"ELEMENT":"75"},{"ELEMENT":"76"},{"ELEMENT":"77"},{"ELEMENT":"78"},{"ELEMENT":"79"},{"ELEMENT":"80"},{"ELEMENT":"81"},{"ELEMENT":"82"},{"ELEMENT":"83"},{"ELEMENTUsing AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desiredCaps = {4};5driver.init(desiredCaps);6driver.sleep(5000).then(function(){7    console.log(elements.length);8    driver.quit();9  });10});11var wd = require('wd');12var assert = require('assert');13var desiredCaps = {14};15driver.init(desiredCaps);16driver.sleep(5000).then(function(){17    console.log(elements.length);18    driver.quit();19  });20});21I am able to get the length of elements using driver.elementsByXPath method. But when I try to get the text of the element using driver.text() method, it gives me the following error:22var wd = require('wd');23var assert = require('assert');24var desiredCaps = {25};Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desiredCaps = {4};5  .init(desiredCaps)6  .then(function (els) {7    console.log('Found', els.length, 'elements');8  })9  .fin(function () { return driver.quit(); })10  .done();11var wd = require('wd');12var assert = require('assert');13var desiredCaps = {14};15  .init(desiredCaps)16  .then(function (els) {17    console.log('Found', els.length, 'elements');18    els[0].getText().then(function(text){19      console.log(text);20    });21  })22  .fin(function () { return driver.quit(); })23  .done();Using AI Code Generation
1var webdriver = require('selenium-webdriver'),2    until = webdriver.until;3var driver = new webdriver.Builder()4    .forBrowser('firefox')5    .build();6driver.findElement(By.name('q')).sendKeys('webdriver');7driver.findElement(By.name('btnG')).click();8driver.wait(until.titleIs('webdriver - Google Search'), 1000);9driver.quit();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!!
