Best JavaScript code snippet using appium-base-driver
utils.test.js
Source:utils.test.js
1import path from 'path'2import { ELEMENT_KEY } from '../src/constants'3import {4 getElementFromResponse,5 getBrowserObject,6 transformToCharString,7 parseCSS,8 checkUnicode,9 findElement,10 findElements,11 verifyArgsAndStripIfElement,12 getElementRect,13 getAbsoluteFilepath,14 assertDirectoryExists,15 validateUrl16} from '../src/utils'17describe('utils', () => {18 describe('getElementFromResponse', () => {19 it('should return null if response is null', () => {20 expect(getElementFromResponse(null)).toBe(null)21 })22 it('should return null if response is undfined', () => {23 expect(getElementFromResponse()).toBe(null)24 })25 it('should find element from JSONWireProtocol response', () => {26 expect(getElementFromResponse({ ELEMENT: 'foobar' })).toBe('foobar')27 })28 it('should find element from W3C response', () => {29 expect(getElementFromResponse({ 'element-6066-11e4-a52e-4f735466cecf': 'barfoo' })).toBe('barfoo')30 })31 it('should throw otherwise', () => {32 expect(getElementFromResponse({ invalid: 'response ' })).toBe(null)33 })34 })35 describe('getBrowserObject', () => {36 it('should traverse up', () => {37 expect(getBrowserObject({38 parent: {39 parent: {40 parent: {41 foo: 'bar'42 }43 }44 }45 })).toEqual({ foo: 'bar' })46 })47 })48 describe('transformToCharString', () => {49 it('should allow to pass non arrays to it', () => {50 expect(transformToCharString('foobar')).toEqual(['f', 'o', 'o', 'b', 'a', 'r'])51 })52 it('should do nothing if all is good', () => {53 expect(transformToCharString(['f'])).toEqual(['f'])54 })55 it('should be able to transform objects', () => {56 expect(transformToCharString({ a: 1 })).toEqual(['{', '"', 'a', '"', ':', '1', '}'])57 })58 it('should be able to transform numbers', () => {59 expect(transformToCharString(42)).toEqual(['4', '2'])60 })61 it('should be able to transform booleans', () => {62 expect(transformToCharString(true)).toEqual(['t', 'r', 'u', 'e'])63 })64 it('ignore undefined/null', () => {65 expect(transformToCharString([null])).toEqual([])66 expect(transformToCharString([undefined])).toEqual([])67 })68 it('can do all of this together', () => {69 expect(transformToCharString(['foo', undefined, { b: 1 }, null, 42, false])).toEqual(70 ['f', 'o', 'o', '{', '"', 'b', '"', ':', '1', '}', '4', '2', 'f', 'a', 'l', 's', 'e'])71 })72 it('should convert string to unicode', () => {73 expect(transformToCharString('Enter')).toEqual(['\uE007'])74 expect(transformToCharString('Back space')).toEqual(['\uE003'])75 expect(transformToCharString('Backspace')).toEqual(['\uE003'])76 expect(transformToCharString('Pageup')).toEqual(['\uE00E'])77 })78 })79 describe('parseCSS', () => {80 it('should return null if css prop is null', () => {81 expect(parseCSS()).toBe(null)82 })83 it('should parse colors properly', () => {84 expect(parseCSS('rgba(0, 136, 204, 1)', 'color')).toEqual({85 property: 'color',86 value: 'rgba(0,136,204,1)',87 parsed: {88 hex: '#0088cc',89 alpha: 1,90 type: 'color',91 rgba: 'rgba(0,136,204,1)'92 }93 })94 expect(parseCSS('#0088cc', 'color')).toEqual({95 property: 'color',96 value: '#0088cc'97 })98 })99 it('should parse fonts properly', () => {100 expect(parseCSS('helvetica', 'font-family')).toEqual({101 property: 'font-family',102 value: 'helvetica',103 parsed: {104 value: ['helvetica'],105 type: 'font',106 string: 'helvetica'107 }108 })109 })110 it('should parse number with unit values', () => {111 expect(parseCSS('100px', 'width')).toEqual({112 property: 'width',113 value: '100px',114 parsed: {115 type: 'number',116 string: '100px',117 unit: 'px',118 value: 100119 }120 })121 expect(parseCSS('50%', 'width')).toEqual({122 property: 'width',123 value: '50%',124 parsed: {125 type: 'number',126 string: '50%',127 unit: '%',128 value: 50129 }130 })131 expect(parseCSS('42', 'foobar')).toEqual({132 property: 'foobar',133 value: 42,134 parsed: {135 type: 'number',136 string: '42',137 unit: '',138 value: 42139 }140 })141 })142 })143 describe('checkUnicode', () => {144 it('should return array with unicode', () => {145 const result = checkUnicode('Home')146 expect(Array.isArray(result)).toBe(true)147 expect(result[0]).toEqual('\uE011')148 })149 it('should return an array without unicode', () => {150 const result = checkUnicode('foo')151 expect(Array.isArray(result)).toBe(true)152 expect(result[0]).toBe('f')153 expect(result[1]).toBe('o')154 expect(result[2]).toBe('o')155 })156 })157 describe('findElement', () => {158 const malformedElementResponse = { foo: 'bar' }159 const elementResponse = { [ELEMENT_KEY]: 'foobar' }160 const elementsResponse = [161 { [ELEMENT_KEY]: 'foobar' },162 { [ELEMENT_KEY]: 'barfoo' }163 ]164 let scope165 beforeEach(() => {166 scope = {167 findElementsFromElement: jest.fn(),168 findElementFromElement: jest.fn(),169 findElements: jest.fn(),170 findElement: jest.fn(),171 execute: jest.fn()172 }173 })174 it('fetches element using a selector string with browser scope', async () => {175 await findElement.call(scope, '.elem')176 expect(scope.findElement).toBeCalledWith('css selector', '.elem')177 expect(scope.findElementFromElement).not.toBeCalled()178 })179 it('fetches element using a selector string with element scope', async () => {180 scope.elementId = 'foobar'181 await findElement.call(scope, '.elem')182 expect(scope.findElement).not.toBeCalled()183 expect(scope.findElementFromElement)184 .toBeCalledWith('foobar', 'css selector', '.elem')185 })186 it('fetches element using a function with browser scope', async () => {187 scope.execute.mockReturnValue(elementResponse)188 const elem = await findElement.call(scope, () => { return global.document.body })189 expect(scope.findElement).not.toBeCalled()190 expect(scope.findElementFromElement).not.toBeCalled()191 expect(scope.execute).toBeCalled()192 expect(elem[ELEMENT_KEY]).toBe('foobar')193 })194 it('fetches element using a function with element scope', async () => {195 scope.elementId = 'foobar'196 scope.execute.mockReturnValue(elementResponse)197 const elem = await findElement.call(scope, () => { return global.document.body })198 expect(scope.findElement).not.toBeCalled()199 expect(scope.findElementFromElement).not.toBeCalled()200 expect(scope.execute).toBeCalled()201 expect(elem[ELEMENT_KEY]).toBe('foobar')202 expect(scope.execute.mock.calls[0][1]).toEqual(scope)203 })204 it('should return only one element if multiple are returned', async () => {205 scope.execute.mockReturnValue(elementsResponse)206 const elem = await findElement.call(scope, () => { return global.document.body })207 expect(scope.findElement).not.toBeCalled()208 expect(scope.findElementFromElement).not.toBeCalled()209 expect(scope.execute).toBeCalled()210 expect(elem[ELEMENT_KEY]).toBe('foobar')211 })212 it('throws if element response is malformed', async () => {213 scope.execute.mockReturnValue(malformedElementResponse)214 const res = await findElement.call(scope, () => { return global.document.body })215 expect(res instanceof Error)216 expect(res.message).toMatch('did not return an HTMLElement')217 })218 it('throws if selector is neither string nor function', async () => {219 const expectedMatch = 'selector needs to be typeof `string` or `function`'220 await expect(findElement.call(scope, null)).rejects.toEqual(new Error(expectedMatch))221 await expect(findElement.call(scope, 123)).rejects.toEqual(new Error(expectedMatch))222 await expect(findElement.call(scope, false)).rejects.toEqual(new Error(expectedMatch))223 await expect(findElement.call(scope)).rejects.toEqual(new Error(expectedMatch))224 })225 })226 describe('findElements', () => {227 const malformedElementResponse = { foo: 'bar' }228 const elementResponse = { [ELEMENT_KEY]: 'foobar' }229 const elementsResponse = [230 { [ELEMENT_KEY]: 'foobar' },231 { [ELEMENT_KEY]: 'barfoo' }232 ]233 let scope234 beforeEach(() => {235 scope = {236 findElementsFromElement: jest.fn(),237 findElementFromElement: jest.fn(),238 findElements: jest.fn(),239 findElement: jest.fn(),240 execute: jest.fn()241 }242 })243 it('fetches element using a selector string with browser scope', async () => {244 await findElements.call(scope, '.elem')245 expect(scope.findElements).toBeCalledWith('css selector', '.elem')246 expect(scope.findElementsFromElement).not.toBeCalled()247 })248 it('fetches element using a selector string with element scope', async () => {249 scope.elementId = 'foobar'250 await findElements.call(scope, '.elem')251 expect(scope.findElements).not.toBeCalled()252 expect(scope.findElementsFromElement)253 .toBeCalledWith('foobar', 'css selector', '.elem')254 })255 it('fetches element using a function with browser scope', async () => {256 scope.execute.mockReturnValue(elementResponse)257 const elem = await findElements.call(scope, () => { return global.document.body })258 expect(scope.findElements).not.toBeCalled()259 expect(scope.findElementsFromElement).not.toBeCalled()260 expect(scope.execute).toBeCalled()261 expect(elem).toHaveLength(1)262 expect(elem[0][ELEMENT_KEY]).toBe('foobar')263 })264 it('fetches element using a function with element scope', async () => {265 scope.elementId = 'foobar'266 scope.execute.mockReturnValue(elementResponse)267 const elem = await findElements.call(scope, () => { return global.document.body })268 expect(scope.findElements).not.toBeCalled()269 expect(scope.findElementsFromElement).not.toBeCalled()270 expect(scope.execute).toBeCalled()271 expect(elem).toHaveLength(1)272 expect(elem[0][ELEMENT_KEY]).toBe('foobar')273 expect(scope.execute.mock.calls[0][1]).toEqual(scope)274 })275 it('should return multiple elements if multiple are returned', async () => {276 scope.execute.mockReturnValue(elementsResponse)277 const elem = await findElements.call(scope, () => { return global.document.body })278 expect(scope.findElement).not.toBeCalled()279 expect(scope.findElementFromElement).not.toBeCalled()280 expect(scope.execute).toBeCalled()281 expect(elem).toEqual(elementsResponse)282 })283 it('should filter out malformed responses', async () => {284 scope.execute.mockReturnValue([...elementsResponse, 'foobar'])285 const elem = await findElements.call(scope, () => { return global.document.body })286 expect(scope.findElement).not.toBeCalled()287 expect(scope.findElementFromElement).not.toBeCalled()288 expect(scope.execute).toBeCalled()289 expect(elem).toEqual(elementsResponse)290 })291 it('throws if element response is malformed', async () => {292 scope.execute.mockReturnValue(malformedElementResponse)293 const res = await findElements.call(scope, () => { return global.document.body })294 expect(res).toHaveLength(0)295 })296 it('throws if selector is neither string nor function', async () => {297 const expectedMatch = 'selector needs to be typeof `string` or `function`'298 await expect(findElements.call(scope, null)).rejects.toEqual(new Error(expectedMatch))299 await expect(findElements.call(scope, 123)).rejects.toEqual(new Error(expectedMatch))300 await expect(findElements.call(scope, false)).rejects.toEqual(new Error(expectedMatch))301 await expect(findElements.call(scope)).rejects.toEqual(new Error(expectedMatch))302 })303 })304 describe('verifyArgsAndStripIfElement', () => {305 class Element {306 constructor({ elementId, ...otherProps }) {307 this.elementId = elementId308 Object.keys(otherProps).forEach(key => this[key] = otherProps[key])309 }310 }311 it('returns the same value if it is not an element object', () => {312 expect(verifyArgsAndStripIfElement([1, 'two', true, false, null, undefined])).toEqual([1, 'two', true, false, null, undefined])313 })314 it('strips down properties if value is element object', () => {315 const fakeObj = new Element({316 elementId: 'foo-bar',317 someProp: 123,318 anotherProp: 'abc'319 })320 expect(verifyArgsAndStripIfElement([fakeObj, 'abc', 123])).toMatchObject([321 { [ELEMENT_KEY]: 'foo-bar', ELEMENT: 'foo-bar' },322 'abc',323 123324 ])325 })326 it('should work even if parameter is not of type Array', () => {327 const fakeObj = new Element({328 elementId: 'foo-bar',329 someProp: 123,330 anotherProp: 'abc'331 })332 expect(verifyArgsAndStripIfElement(fakeObj)).toMatchObject(333 { [ELEMENT_KEY]: 'foo-bar', ELEMENT: 'foo-bar' }334 )335 expect(verifyArgsAndStripIfElement('foo')).toEqual('foo')336 })337 it('throws error if element object is missing element id', () => {338 const fakeObj = new Element({339 someProp: 123,340 anotherProp: 'abc',341 selector: 'div'342 })343 expect(() => verifyArgsAndStripIfElement(fakeObj)).toThrow('The element with selector "div" you trying to pass into the execute method wasn\'t found')344 })345 })346 describe('getElementRect', () => {347 it('uses getBoundingClientRect if a key is missing', async () => {348 const fakeScope = {349 elementId: 123,350 getElementRect: jest.fn(() => Promise.resolve({ x: 10, width: 300, height: 400 })),351 execute: jest.fn(() => Promise.resolve({ x: 11, y: 22, width: 333, height: 444 }))352 }353 expect(await getElementRect(fakeScope)).toEqual({ x: 10, y: 22, width: 300, height: 400 })354 expect(fakeScope.getElementRect).toHaveBeenCalled()355 expect(fakeScope.execute).toHaveBeenCalled()356 })357 })358 describe('getAbsoluteFilepath', () => {359 it('should not change filepath if starts with forward slash', () => {360 const filepath = '/packages/bar.png'361 expect(getAbsoluteFilepath(filepath)).toEqual(filepath)362 })363 it('should not change filepath if starts with backslash slash', () => {364 const filepath = '\\packages\\bar.png'365 expect(getAbsoluteFilepath(filepath)).toEqual(filepath)366 })367 it('should not change filepath if starts with windows drive letter', async () => {368 const filepath = 'E:\\foo\\bar.png'369 expect(getAbsoluteFilepath(filepath)).toEqual(filepath)370 })371 it('should change filepath if does not start with forward or back slash', async () => {372 const filepath = 'packages/bar.png'373 expect(getAbsoluteFilepath(filepath)).toEqual(path.join(process.cwd(), 'packages/bar.png'))374 })375 })376 describe('assertDirectoryExists', () => {377 it('should fail if not existing directory', () => {378 expect(() => assertDirectoryExists('/i/dont/exist.png')).toThrowError(new Error('directory (/i/dont) doesn\'t exist'))379 })380 it('should not fail if directory exists', () => {381 expect(() => assertDirectoryExists('.')).not.toThrow()382 })383 })384 describe('validateUrl', () => {385 it('should ensure url is correct', () => {386 expect(validateUrl('http://json.org')).toEqual('http://json.org/')387 expect(validateUrl('www.json.org')).toEqual('http://www.json.org/')388 expect(validateUrl('json.org')).toEqual('http://json.org/')389 expect(validateUrl('about:blank')).toEqual('about:blank')390 expect(validateUrl('IamInAHost')).toEqual('http://iaminahost/')391 expect(validateUrl('data:text/html, <html contenteditable>'))392 .toEqual('data:text/html, <html contenteditable>')393 expect(() => validateUrl('_I.am.I:nvalid'))394 .toThrowError('Invalid URL: _I.am.I:nvalid')395 })396 })...
utils.js
Source:utils.js
1export const find_by_id = async (driver, id) => {2 let element = await driver.findElement('id', `com.instagram.android:id/${id}`)3 if (element != null) return element['ELEMENT']4 return null5}6export const finds_by_id = async (driver, id) => {7 let result = []8 let elements = await driver.findElements('id', `com.instagram.android:id/${id}`)9 if (elements.length > 0) {10 elements.forEach(e => {11 result.push(e['ELEMENT'])12 });13 }14 return result15}16export const find_by_class = async (driver, className) => {17 let element = await driver.findElement('class name', className)18 if (element != null) return element['ELEMENT']19 return null20}21export const finds_by_class = async (driver, className) => {22 let result = []23 let elements = await driver.findElements('class name', className)24 if (elements.length > 0) {25 elements.forEach(e => {26 result.push(e['ELEMENT'])27 });28 }29 return result30}31export const find_by_accessibility_id = async (driver, accessibilityId) => {32 let element = await driver.findElement('accessibility id', accessibilityId)33 if (element != null) return element['ELEMENT']34 return null35}36export const finds_by_accessibility_id = async (driver, accessibilityId) => {37 let result = []38 let elements = await driver.findElements('accessibility id', accessibilityId)39 if (elements.length > 0) {40 elements.forEach(e => {41 result.push(e['ELEMENT'])42 });43 }44 return result45}46export const find_child_by_id = async (driver, eParent, id) => {47 let elementChild = await driver.findElementFromElement(eParent, 'id', `com.instagram.android:id/${id}`)48 if (elementChild != null) return elementChild['ELEMENT']49 return null50}51export const finds_child_by_id = async (driver, eParent, id) => {52 let result = []53 let elementsChild = await driver.findElementsFromElement(eParent, 'id', `com.instagram.android:id/${id}`)54 if (elementsChild.length > 0) {55 elementsChild.forEach(e => {56 result.push(e['ELEMENT'])57 });58 }59 return result60}61export const find_child_by_class = async (driver, eParent, className) => {62 let elementChild = await driver.findElementFromElement(eParent, 'class name', className)63 if (elementChild != null) return elementChild['ELEMENT']64 return null65}66export const finds_child_by_class = async (driver, eParent, className) => {67 let result = []68 let elementsChild = await driver.findElementsFromElement(eParent, 'class name', className)69 if (elementsChild.length > 0) {70 elementsChild.forEach(e => {71 result.push(e['ELEMENT'])72 });73 }74 return result75}76export const find_child_by_accessibility_id = async (driver, eParent, accessibilityId) => {77 let elementChild = await driver.findElementFromElement(eParent, 'accessibility id', accessibilityId)78 if (elementChild != null) return elementChild['ELEMENT']79 return null80}81export const finds_child_by_accessibility_id = async (driver, eParent, accessibilityId) => {82 let result = []83 let elementsChild = await driver.findElementsFromElement(eParent, 'accessibility id', accessibilityId)84 if (elementsChild.length > 0) {85 elementsChild.forEach(e => {86 result.push(e['ELEMENT'])87 });88 }89 return result...
glassDoorApproval.js
Source:glassDoorApproval.js
1import { checkCssProperty } from '../../helpers/helpers';2import { onDesktop, onMobile, onTabletLandscape, onTabletPortrait } from '../../helpers/enviromentTypes';3describe('Glassdoor Widget Approval Item', () => {4 beforeEach(() => {5 browser.url('/about/careers.html');6 });7 /**8 * Objects9 */10 const isIE = $$('.ie11');11 const glassdoorWidget = $$('.glassdoorWidget.slick-carousel');12 const glassdoorItemApproval = browser.findElementFromElement(glassdoorWidget, '.glassdoor-item-approval');13 const approvalSection = browser.findElementFromElement(glassdoorItemApproval, '.glassdoorWidgetComponent.approval');14 const approvalContainer = browser.findElementFromElement(approvalSection, '.glassdoorWidgetComponent.approval .approval-container');15 const circleRating = browser.findElementFromElement(approvalContainer, '.circle-rating');16 const circleContainer = browser.findElementFromElement(circleRating, '.circle-container');17 const valueRating = browser.findElementFromElement(circleContainer, '.value-rating');18 const progressBar = browser.findElementFromElement(valueRating, '.progress-bar');19 const progressMeter = browser.findElementFromElement(progressBar, '.progress-meter');20 const progressValue = browser.findElementFromElement(progressBar, '.progress-value');21 const approvalImg = browser.findElementFromElement(approvalContainer, '.approval-img');22 const approvalDescription = browser.findElementFromElement(approvalContainer, '.approval-description');23 const approvalPosition = browser.findElementFromElement(approvalDescription, '.approval-position');24 const approvalUsername = browser.findElementFromElement(approvalDescription, '.approval-username');25 const poweredGd = browser.findElementFromElement(approvalSection, '.powered-gd');26 const img = browser.findElementFromElement(poweredGd, 'img');27 /* Desktop */28 describe('Desktop', () => {29 onDesktop();30 it('The each widget within 4 column grid which is ~ 33.33%', async () => {31 let columnGridWidth = glassdoorWidget.getSize() / 3;32 assert.strictEqual(columnGridWidth, '33.33%');33 });34 // it('Checking styles for ".progress-meter" section', () => {35 // checkCssProperty(GlassDoorComponent.progressMeter, [['stroke-width', '19px']]);36 // });37 });38 // /* Mobile */39 // describe('Mobile', () => {40 // onMobile();41 // it('Need has three columns on Mobile', async () => {42 // await onMobile();43 // await checkCountBlocks();44 // });45 // });46 // /* onTabletLandscape */47 // describe('TabletLandscape', () => {48 // onTabletLandscape();49 // it('Need has three columns on TabletLandscape', async () => {50 // await await checkCountBlocks();51 // });52 // });53 // /* onTabletPortrait */54 // describe('TabletPortrait', () => {55 // onTabletPortrait();56 // it('Need has three columns on TabletPortrait', async () => {57 // await await checkCountBlocks();58 // });59 // });...
from-el-e2e-specs.js
Source:from-el-e2e-specs.js
1import chai from 'chai';2import chaiAsPromised from 'chai-as-promised';3import AndroidDriver from '../../../..';4import DEFAULT_CAPS from '../../desired';5import { util } from 'appium-support';6chai.should();7chai.use(chaiAsPromised);8const atv = 'android.widget.TextView';9const alv = 'android.widget.ListView';10describe('Find - from element', function () {11 let driver;12 let parentEl;13 before(async function () {14 driver = new AndroidDriver();15 await driver.createSession(DEFAULT_CAPS);16 parentEl = await driver.findElement('class name', alv);17 parentEl = util.unwrapElement(parentEl);18 });19 after(async function () {20 await driver.deleteSession();21 });22 it('should find a single element by tag name', async function () {23 let innerEl = await driver.findElementFromElement('class name', atv, parentEl);24 await driver.getText(innerEl.ELEMENT).should.eventually.equal("Access'ibility");25 });26 it('should find multiple elements by tag name', async function () {27 let innerEl = await driver.findElementsFromElement('class name', atv, parentEl);28 await driver.getText(innerEl[0].ELEMENT).should.eventually.have.length.above(10);29 });30 it('should not find an element that does not exist', async function () {31 await driver.findElementFromElement('class name', 'blargimarg', parentEl)32 .should.be.rejectedWith(/could not be located/);33 });34 it('should not find multiple elements that do not exist', async function () {35 await driver.findElementFromElement('class name', 'blargimarg', parentEl)36 .should.be.rejectedWith(/could not be located/);37 });...
elementIdElement.js
Source:elementIdElement.js
1'use strict';2const proxyquire = require('proxyquire');3const {mkBrowser_} = require('../../../utils');4describe('"elementIdElement" command', () => {5 let browser, findStrategy, addElementIdElement;6 beforeEach(() => {7 browser = mkBrowser_();8 findStrategy = sinon.stub().returns({});9 addElementIdElement = proxyquire('lib/commands/protocol/elementIdElement', {10 '../../helpers/findStrategy': findStrategy11 });12 });13 afterEach(() => sinon.restore());14 it('should add "elementIdElement" command', () => {15 addElementIdElement(browser);16 assert.calledOnceWithExactly(browser.addCommand, 'elementIdElement', sinon.match.func);17 });18 it('should find selector strategy by passed selector', async () => {19 addElementIdElement(browser);20 await browser.elementIdElement('element-id', '.some-selector');21 assert.calledOnceWithExactly(findStrategy, '.some-selector');22 });23 it('should call "findElementFromElement" with passed element id, selector strategy and selector', async () => {24 const browser = mkBrowser_();25 const using = 'css selector';26 const selector = '.some-selector';27 findStrategy.withArgs(selector).returns({using, value: selector});28 addElementIdElement(browser);29 await browser.elementIdElement('element-id', selector);30 assert.calledOnceWithExactly(browser.findElementFromElement, 'element-id', using, selector);31 });...
findElementFromElement.js
Source:findElementFromElement.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.default = findElementFromElement;6var _constants = require("../constants");7var _utils = require("../utils");8async function findElementFromElement({9 elementId,10 using,11 value12}) {13 if (!_constants.SUPPORTED_SELECTOR_STRATEGIES.includes(using)) {14 throw new Error(`selector strategy "${using}" is not yet supported`);15 }16 const elementHandle = this.elementStore.get(elementId);17 if (!elementHandle) {18 throw (0, _utils.getStaleElementError)(elementId);19 }20 if (using === 'link text') {21 using = 'xpath';22 value = `.//a[normalize-space() = "${value}"]`;23 } else if (using === 'partial link text') {24 using = 'xpath';25 value = `.//a[contains(., "${value}")]`;26 }27 return _utils.findElement.call(this, elementHandle, using, value);...
find-element-from-element.js
Source:find-element-from-element.js
1import Endpoint from '..'2import { MissingCommandParameters } from '../../utils/errors.js'3class FindElementFromElement extends Endpoint {4 static create (req) {5 let {using, value} = req.body6 if (!using) {7 throw new MissingCommandParameters('strategy required for FindElement')8 }9 return new FindElementFromElement([using, value, req.params.id])10 }11}12FindElementFromElement.method = 'post'13FindElementFromElement.url = '/session/:sessionId/element/:id/element'...
getChildName.js
Source:getChildName.js
1export default async function getChildName(parentElement, childId) {2 const child = await this.driver.findElementFromElement(3 parentElement,4 childId5 )6 const text = await this.driver.getElementText(7 child.value.ELEMENT8 )9 return text.value...
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2 build();3var searchBox = driver.findElement(webdriver.By.name('q'));4searchBox.sendKeys('webdriver');5searchBox.getAttribute('value').then(function(value) {6});7driver.quit();
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3 .withCapabilities({'app': 'com.example.android.apis', 'appActivity': '.ApiDemos', 'appPackage': 'com.example.android.apis', 'platformName': 'Android', 'platformVersion': '4.4.2', 'deviceName': 'Android Emulator'})4 .build();5driver.findElement(webdriver.By.id('android:id/list')).then(function(el) {6 el.findElement(webdriver.By.name('App')).then(function(el2) {7 el2.click();8 });9});10driver.quit();11[debug] [AndroidBootstrap] Sending command to android: {"cmd":"action","action":"find","params":{"strategy":"id","selector":"android:id/list","context":"","multiple":false}}12[debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"action","action":"find","params":{"strategy":"id","selector":"android:id/list","context":"","multiple":false}}13[debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Returning result: {"status":0,"value":{"ELEMENT":"1"}}14[debug] Responding to client with success: {"status":0,"value":{"ELEMENT":"1"},"sessionId":"c9a9e3b3-3e2f-4a6c-9c3a-6c2e6d9f6a9d"}15[debug] [AndroidBootstrap] Sending command to android: {"cmd":"action","action":"find","params":{"strategy":"name","selector":"App","context
Using AI Code Generation
1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4const {exec} = require('teen_process');5const {fs, tempDir} = require('appium-support');6chai.should();7chai.use(chaiAsPromised);8const PORT = 4723;9const HOST = 'localhost';10const DEFAULT_CAPS = {
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desired = {4};5var d = wd.promiseChainRemote("localhost", 4723);6d.init(desired).then(function () {7 return d.elementById('com.example.android.contactmanager:id/addContactButton');8}).then(function (el) {9 return d.findElementFromElement(el, 'id', 'com.example.android.contactmanager:id/contactNameEditText');10}).then(function (el) {11 return d.type(el, 'Appium User');12}).then(function () {13 return d.elementById('com.example.android.contactmanager:id/contactEmailEditText');14}).then(function (el) {15 return d.type(el, '
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!!