How to use d.findElementsFromElement method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

utils.test.js

Source:utils.test.js Github

copy

Full Screen

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 })...

Full Screen

Full Screen

find-specs.js

Source:find-specs.js Github

copy

Full Screen

1import env from '../helpers/env';2import setup from "../setup-base";3import desired from './desired';4import B from 'bluebird';5import _ from 'lodash';6import { clickButton, throwMatchableError, filterDisplayed,7 filterVisibleUiaSelector } from '../helpers/recipes';8const byUIA = '-ios uiautomation';9describe('uicatalog - find -', function () {10 let session = setup(this, desired);11 let driver = session.driver;12 describe('basics', function () {13 it('should find a single element by id', async function () {14 let el = await driver.findElement('id', 'Date Picker');15 el.should.exist;16 });17 it('should find a single element by id wrapped in array for multi', async function () {18 let els = await driver.findElements('id', 'Back');19 els.should.have.length(1);20 });21 it('should find a single element using elementByAccessibilityId', async function () {22 let axId = (env.IOS8 || env.IOS9)23 ? 'AAPLImageViewController'24 : 'Image View, AAPLImageViewController';25 let el = await driver.findElement('accessibility id', axId);26 el.should.exist;27 });28 it('should find an element within descendants', async function () {29 let el1 = await driver.findElement('xpath', "//UIATableCell[contains(@name, 'Buttons')]");30 el1.should.exist;31 let el2 = await driver.findElementFromElement('class name', 'UIAStaticText', el1);32 (await driver.getAttribute('name', el2)).should.contain("Buttons");33 });34 it('should not find an element not within itself', async function () {35 let el1 = await driver.findElement('xpath', "//UIATableCell[contains(@name, 'Buttons')]");36 el1.should.exist;37 await B.resolve(driver.findElementFromElement('class name', 'UIANavigationBar', el1))38 .catch(throwMatchableError)39 .should.be.rejectedWith(/jsonwpCode: 7/);40 });41 it('should find some elements within itself', async function () {42 let elLength = (env.IOS8 || env.IOS9) ? 2 : 1;43 let el1 = await driver.findElement('xpath', "//UIATableCell[contains(@name, 'Buttons')]");44 el1.should.exist;45 let els = await driver.findElementsFromElement('class name', 'UIAStaticText', el1);46 els.should.have.length(elLength);47 });48 it('should not find elements not within itself', async function () {49 let el1 = await driver.findElement('xpath', "//UIATableCell[contains(@name, 'Buttons')]");50 el1.should.exist;51 let els = await driver.findElementsFromElement('class name', 'UIANavigationBar', el1);52 els.should.have.length(0);53 });54 describe('no mix up', function () {55 after(async function () {56 if (!env.IOS81 && !env.IOS82 && !env.IOS83 && !env.IOS84 && !env.IOS9) {57 await clickButton(driver, 'UICatalog');58 }59 });60 it('should not allow found elements to be mixed up', async function () {61 let el1 = await driver.findElement('class name', 'UIATableCell');62 let el1Name = await driver.getAttribute('name', el1);63 await driver.click(el1);64 await B.delay(1000);65 let el2 = await driver.findElement('class name', 'UIATableCell');66 let el2Name = await driver.getAttribute('name', el2);67 el1.ELEMENT.should.not.equal(el2.ELEMENT);68 el1Name.should.not.equal(el2Name);69 // el1 is gone, so it doesn't have a name anymore70 (await driver.getAttribute('name', el1)).should.equal("");71 });72 });73 it('should return all image elements with internally generated ids', async function () {74 let els = await driver.findElements('class name', 'UIAImage');75 els.length.should.be.above(0);76 for (let el of els) {77 el.should.exist;78 }79 });80 describe('findElementsByClassName textfield case', function () {81 after(async function () {82 if (!env.IOS81 && !env.IOS82 && !env.IOS83 && !env.IOS84 && !env.IOS9) {83 await clickButton(driver, 'UICatalog');84 }85 });86 let axIdExt = (env.IOS8 || env.IOS9) ? '' : ', AAPLActionSheetViewController';87 it('should find only one textfield', async function () {88 let el1 = await driver.findElement('accessibility id', `Action Sheets${axIdExt}`);89 await driver.click(el1);90 let el2 = await driver.findElement('accessibility id', 'Okay / Cancel');91 let els = await driver.findElementsFromElement('class name', 'UIAStaticText', el2);92 els.should.have.length(1);93 });94 });95 describe('findElement(s) containing accessibility id', function () {96 afterEach(async function () {97 await clickButton(driver, 'UICatalog');98 await B.delay(1000);99 });100 let axIdExt = (env.IOS8 || env.IOS9) ? '' : ', AAPLActionSheetViewController';101 it('should find one element', async function () {102 let el1 = await driver.findElement('accessibility id', `Action Sheets${axIdExt}`);103 await driver.click(el1);104 let el2 = await driver.findElement('accessibility id', 'Okay / Cancel');105 (await driver.getAttribute('name', el2)).should.equal('Okay / Cancel');106 });107 it('should find several elements', async function () {108 let el1 = await driver.findElement('accessibility id', `Action Sheets${axIdExt}`);109 await driver.click(el1);110 let el2 = await driver.findElements('accessibility id', 'Okay / Cancel');111 el2.should.have.length(2);112 });113 });114 describe('duplicate text field', function () {115 beforeEach(async function () {116 try {117 await driver.execute("mobile: scroll", {direction: 'down'});118 } catch (ign) {}119 });120 afterEach(async function () {121 await clickButton(driver, 'UICatalog');122 await B.delay(1000);123 });124 let axIdExt = (env.IOS8 || env.IOS9) ? '' : ', AAPLTextFieldViewController';125 it('should find only one element per text field', async function () {126 let el1 = await driver.findElement('accessibility id', `Text Fields${axIdExt}`);127 await driver.click(el1);128 B.delay(2000);129 let els = await driver.findElements('class name', 'UIATextField');130 els.should.have.length(4);131 });132 it('should find only one element per secure text field', async function () {133 let el1 = await driver.findElement('accessibility id', `Text Fields${axIdExt}`);134 await driver.click(el1);135 B.delay(2000);136 let els = await driver.findElements('class name', 'UIASecureTextField');137 els.should.have.length(1);138 });139 });140 });141 describe('by accessibility id', function () {142 afterEach(async function () {143 await clickButton(driver, 'UICatalog');144 });145 it('should find an element by name beneath another element', async function () {146 let axIdExt = env.IOS8 || env.IOS9 ? '' : ', AAPLActionSheetViewController';147 let el = await driver.findElement('accessibility id', "UICatalog");148 await driver.click(el);149 let el2 = await driver.findElement('accessibility id', `Action Sheets${axIdExt}`);150 el2.should.exist;151 });152 });153 describe('by ui automation', function () {154 before(async function () {155 let el = await driver.findElement(byUIA, '.navigationBars()[0]');156 if ((await driver.getAttribute('name', el)) !== 'UICatalog') {157 await clickButton(driver, 'UICatalog');158 }159 await B.delay(500);160 });161 it('should process most basic UIAutomation query', async function () {162 let els = await driver.findElements(byUIA, '.elements()');163 let displayedEls = await filterDisplayed(driver, els);164 displayedEls.should.have.length(2);165 });166 it('should use raw selector code if selector does not start with a dot', async function () {167 let els = await driver.findElements(byUIA, '$.mainWindow().elements()');168 let displayedEls = await filterDisplayed(driver, els);169 displayedEls.should.have.length(2);170 });171 it('should get a single element', async function () {172 let el = await driver.findElement(byUIA, '.elements()[0]');173 (await driver.getAttribute('name', el)).should.equal('UICatalog');174 });175 it('should get a single element with non-zero index', async function () {176 let name = env.IOS8 || env.IOS9 ? '' : 'Empty list';177 let el = await driver.findElement(byUIA, '.elements()[1]');178 (await driver.getAttribute('name', el)).should.equal(name);179 });180 it('should get single element as array', async function () {181 let els = await driver.findElements(byUIA, '.tableViews()[0]');182 els.should.have.length(1);183 });184 it('should find elements by index multiple times', async function () {185 let el = await driver.findElement(byUIA, '.elements()[1].cells()[2]');186 (await driver.getAttribute('name', el)).should.include('Alert Views');187 });188 it('should find element by name', async function () {189 let el = await driver.findElement(byUIA, '.elements()["UICatalog"]');190 (await driver.getAttribute('name', el)).should.equal('UICatalog');191 });192 it('should find element by type and index', async function () {193 let el = await driver.findElement(byUIA, '.navigationBar().elements()[1]');194 (await driver.getAttribute('name', el)).should.equal('Back');195 });196 describe('start from a given context instead of root target', function () {197 it('should process a simple query', async function () {198 let el = await driver.findElement(byUIA, '.elements()[1]');199 let els = await driver.findElementsFromElement(byUIA, filterVisibleUiaSelector('.elements();'), el);200 els.should.have.length.at.least(10);201 });202 it('should find element by name', async function () {203 let axIdExt = env.IOS8 || env.IOS9 ? "" : ", AAPLButtonViewController";204 let el1 = await driver.findElement(byUIA, '.elements()[1]');205 let el2 = await driver.findElementFromElement(byUIA, `.elements()["Buttons${axIdExt}"]`, el1);206 el2.should.exist;207 });208 });209 });210 describe('by xpath', function () {211 describe('individual calls', function () {212 before(async function () {213 // before anything, try to go back214 try {215 let el = await driver.findElement(byUIA, '.navigationBar().elements()[1]');216 await driver.click(el);217 } catch (ign) {}218 // and make sure we are at the top of the page219 try {220 await driver.execute("mobile: scroll", {direction: 'up'});221 } catch (ign) {}222 });223 beforeEach(async function () {224 // go into the right page225 let el = await driver.findElement('xpath', "//UIAStaticText[contains(@label,'Buttons')]");226 await driver.click(el);227 });228 afterEach(async function () {229 // go back230 let el = await driver.findElement(byUIA, '.navigationBar().elements()[1]');231 await driver.click(el);232 });233 it('should respect implicit wait', async function () {234 await driver.implicitWait(5000);235 let begin = Date.now();236 await driver.findElement('xpath', "//something_not_there")237 .should.eventually.be.rejected;238 let end = Date.now();239 (end - begin).should.be.above(5000);240 });241 it('should return the last button', async function () {242 let el = await driver.findElement('xpath', "//UIAButton[last()]");243 (await driver.getText(el)).should.equal("Button"); // this is the name of the last button244 });245 it('should return a single element', async function () {246 let el = await driver.findElement('xpath', "//UIAButton");247 (await driver.getText(el)).should.equal("UICatalog");248 });249 it('should return multiple elements', async function () {250 let els = await driver.findElements('xpath', "//UIAButton");251 els.should.have.length.above(5);252 });253 it('should filter by name', async function () {254 let el = await driver.findElement('xpath', "//UIAButton[@name='X Button']");255 (await driver.getText(el)).should.equal("X Button");256 });257 it('should know how to restrict root-level elements', async function () {258 await B.resolve(driver.findElement('xpath', "/UIAButton"))259 .catch(throwMatchableError)260 .should.be.rejectedWith(/jsonwpCode: 7/);261 });262 it('should search an extended path by child', async function () {263 let el = await driver.findElement('xpath', "//UIANavigationBar/UIAStaticText");264 (await driver.getText(el)).should.equal('Buttons');265 });266 it('should search an extended path by descendant', async function () {267 let els = await driver.findElements('xpath', "//UIATableCell//UIAButton");268 let texts = await B.all(_.map(els, (el) => { return driver.getText(el); }));269 texts.should.not.include("UICatalog");270 texts.should.include("X Button");271 });272 it('should filter by indices', async function () {273 await driver.implicitWait(10000);274 let el = await driver.findElement('xpath', "//UIATableCell[4]/UIAButton[1]");275 (await driver.getAttribute('name', el)).should.equal('X Button');276 });277 it('should filter by partial text', async function () {278 let el = await driver.findElement('xpath', "//UIATableCell//UIAButton[contains(@name, 'X ')]");279 (await driver.getText(el)).should.equal("X Button");280 });281 it('should find an element within itself', async function () {282 let e1 = await driver.findElement('xpath', "//UIATableCell[@name='X Button']");283 let e2 = await driver.findElementFromElement('xpath', "//UIAButton[1]", e1);284 (await driver.getText(e2)).should.equal("X Button");285 });286 });287 describe('duplicate text field', function () {288 beforeEach(async function () {289 let el = await driver.findElement('accessibility id', 'Text Fields');290 await driver.click(el);291 await B.delay(2000);292 });293 afterEach(async function () {294 let el = await driver.findElement('accessibility id', 'UICatalog');295 await driver.click(el);296 await B.delay(1000);297 });298 it('should find only one text field', async function () {299 let els = await driver.findElements('xpath', '//UIATableView["Empty list"]/UIATableCell[1]/UIATextField');300 els.should.have.length(1);301 });302 it('should find only one text field when doing relative search', async function () {303 let el2 = await driver.findElement('xpath', '//UIATableView["Empty list"]');304 let els = await driver.findElementsFromElement('xpath', '//UIATableCell[1]/UIATextField', el2);305 els.should.have.length(1);306 });307 it('should find only one secure text field', async function () {308 let els = await driver.findElements('xpath', '//UIATableView["Empty list"]/UIATableCell[3]/UIASecureTextField');309 els.should.have.length(1);310 });311 });312 describe('multiple calls', function () {313 let runs = 5;314 let test = function (path, minLength) {315 return function () {316 it('should not crash', async function () {317 let els = await driver.findElements('xpath', path);318 els.should.have.length.above(minLength);319 });320 };321 };322 describe('finding specific path', function () {323 for (let n = 0; n < runs; n++) {324 describe(`test ${n + 1}`, test("//UIAApplication[1]/UIAWindow/UIATableView/UIATableCell", 17));325 }326 });327 describe('finding //*', function () {328 for (let n = 0; n < runs; n++) {329 describe(`test ${n + 1}`, test("//*", 52));330 }331 });332 });333 });...

Full Screen

Full Screen

utils.js

Source:utils.js Github

copy

Full Screen

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...

Full Screen

Full Screen

find.js

Source:find.js Github

copy

Full Screen

1import _ from 'lodash';2import { errors } from 'appium-base-driver';3import { FakeElement } from '../fake-element';4let commands = {}, helpers = {}, extensions = {};5helpers.getExistingElementForNode = function getExistingElementForNode (node) {6 for (let [id, el] of _.toPairs(this.elMap)) {7 if (el.node === node) {8 return id;9 }10 }11 return null;12};13helpers.wrapNewEl = function wrapNewEl (obj) {14 // first check and see if we already have a ref to this element15 let existingElId = this.getExistingElementForNode(obj);16 if (existingElId) {17 return {ELEMENT: existingElId};18 }19 // otherwise add the element to the map20 this.maxElId++;21 this.elMap[this.maxElId.toString()] = new FakeElement(obj, this.appModel);22 return {ELEMENT: this.maxElId.toString()};23};24helpers.findElOrEls = async function findElOrEls (strategy, selector, mult, ctx) {25 let qMap = {26 'xpath': 'xpathQuery',27 'id': 'idQuery',28 'accessibility id': 'idQuery',29 'class name': 'classQuery',30 'tag name': 'classQuery'31 };32 // TODO this error checking should probably be part of MJSONWP?33 if (!_.includes(_.keys(qMap), strategy)) {34 throw new errors.UnknownCommandError();35 }36 if (selector === 'badsel') {37 throw new errors.InvalidSelectorError();38 }39 let els = this.appModel[qMap[strategy]](selector, ctx);40 if (els.length) {41 if (mult) {42 let allEls = [];43 for (let el of els) {44 allEls.push(this.wrapNewEl(el));45 }46 return allEls;47 } else {48 return this.wrapNewEl(els[0]);49 }50 } else if (mult) {51 return [];52 } else {53 throw new errors.NoSuchElementError();54 }55};56commands.findElement = async function findElement (strategy, selector) {57 return this.findElOrEls(strategy, selector, false);58};59commands.findElements = async function findElements (strategy, selector) {60 return this.findElOrEls(strategy, selector, true);61};62commands.findElementFromElement = async function findElementFromElement (strategy, selector, elementId) {63 let el = this.getElement(elementId);64 return this.findElOrEls(strategy, selector, false, el.xmlFragment);65};66commands.findElementsFromElement = async function findElementsFromElement (strategy, selector, elementId) {67 let el = this.getElement(elementId);68 return this.findElOrEls(strategy, selector, true, el.xmlFragment);69};70Object.assign(extensions, commands, helpers);71export { commands, helpers};...

Full Screen

Full Screen

selectByIndex.js

Source:selectByIndex.js Github

copy

Full Screen

1/**2 *3 * Select option with a specific index.4 *5 * <example>6 :example.html7 <select id="selectbox">8 <option value="someValue0">uno</option>9 <option value="someValue1">dos</option>10 <option value="someValue2">tres</option>11 <option value="someValue3">cuatro</option>12 <option value="someValue4">cinco</option>13 <option value="someValue5">seis</option>14 </select>15 :selectByIndex.js16 it('Should demonstrate the selectByIndex command', () => {17 const selectBox = $('#selectbox');18 console.log(selectBox.getValue()); // returns "someValue0"19 selectBox.selectByIndex(4);20 console.log(selectBox.getValue()); // returns "someValue4"21 });22 * </example>23 *24 * @alias element.selectByIndexs25 * @param {Number} index option index26 * @uses protocol/findElementsFromElement, protocol/elementClick27 * @type action28 *29 */30import { getElementFromResponse } from '../../utils'31export default async function selectByIndex (index) {32 /**33 * negative index check34 */35 if (index < 0) {36 throw new Error('Index needs to be 0 or any other positive number')37 }38 /**39 * get option elememnts using css40 */41 const optionElements = await this.findElementsFromElement(this.elementId, 'css selector', 'option')42 if (optionElements.length === 0) {43 throw new Error('Select element doesn\'t contain any option element')44 }45 if (optionElements.length - 1 < index) {46 throw new Error(`Option with index "${index}" not found. Select element only contains ${optionElements.length} option elements`)47 }48 /**49 * select option50 */51 return this.elementClick(getElementFromResponse(optionElements[index]))...

Full Screen

Full Screen

from-el-e2e-specs.js

Source:from-el-e2e-specs.js Github

copy

Full Screen

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 });...

Full Screen

Full Screen

elementIdElements.js

Source:elementIdElements.js Github

copy

Full Screen

1'use strict';2const proxyquire = require('proxyquire');3const {mkBrowser_} = require('../../../utils');4describe('"elementIdElements" command', () => {5 let browser, findStrategy, addElementIdElements;6 beforeEach(() => {7 browser = mkBrowser_();8 findStrategy = sinon.stub().returns({});9 addElementIdElements = proxyquire('lib/commands/protocol/elementIdElements', {10 '../../helpers/findStrategy': findStrategy11 });12 });13 afterEach(() => sinon.restore());14 it('should add "elementIdElement" command', () => {15 addElementIdElements(browser);16 assert.calledOnceWithExactly(browser.addCommand, 'elementIdElements', sinon.match.func);17 });18 it('should find selector strategy by passed selector', async () => {19 addElementIdElements(browser);20 await browser.elementIdElements('element-id', '.some-selector');21 assert.calledOnceWithExactly(findStrategy, '.some-selector');22 });23 it('should call "findElementsFromElement" 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 addElementIdElements(browser);29 await browser.elementIdElements('element-id', selector);30 assert.calledOnceWithExactly(browser.findElementsFromElement, 'element-id', using, selector);31 });...

Full Screen

Full Screen

find-elements-from-element.js

Source:find-elements-from-element.js Github

copy

Full Screen

1import Endpoint from '..'2import { MissingCommandParameters } from '../../utils/errors.js'3class FindElementsFromElement extends Endpoint {4 static create (req) {5 let {using, value} = req.body6 if (!using) {7 throw new MissingCommandParameters('strategy required for FindElements')8 }9 return new FindElementsFromElement([using, value, req.params.id])10 }11}12FindElementsFromElement.method = 'post'13FindElementsFromElement.url = '/session/:sessionId/element/:id/elements'...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var By = webdriver.By;3var until = webdriver.until;4var driver = new webdriver.Builder()5 .forBrowser('chrome')6 .build();7driver.findElement(By.name('q')).sendKeys('webdriver');8driver.findElement(By.name('btnG')).click();9driver.wait(until.titleIs('webdriver - Google Search'), 1000);10driver.findElement(By.name('q')).sendKeys('webdriver');11driver.findElement(By.name('btnG')).click();12driver.wait(until.titleIs('webdriver - Google Search'), 1000);13driver.findElement(By.name('q')).sendKeys('webdriver');14driver.findElement(By.name('btnG')).click();15driver.wait(until.titleIs('webdriver - Google Search'), 1000);16driver.findElement(By.name('q')).sendKeys('webdriver');17driver.findElement(By.name('btnG')).click();18driver.wait(until.titleIs('webdriver - Google Search'), 1000);19driver.findElement(By.name('q')).sendKeys('webdriver');20driver.findElement(By.name('btnG')).click();21driver.wait(until.titleIs('webdriver - Google Search'), 1000);22driver.findElement(By.name('q')).sendKeys('webdriver');23driver.findElement(By.name('btnG')).click();24driver.wait(until.titleIs('webdriver - Google Search'), 1000);25driver.findElement(By.name('q')).sendKeys('webdriver');26driver.findElement(By.name('btnG')).click();27driver.wait(until.titleIs('webdriver - Google Search'), 1000);28driver.findElement(By.name('q')).sendKeys('webdriver');29driver.findElement(By.name('btnG')).click();30driver.wait(until.titleIs('webdriver - Google Search'), 1000);31driver.findElement(By.name('q')).sendKeys('webdriver');32driver.findElement(By.name('btnG')).click();33driver.wait(until.titleIs('webdriver - Google Search'), 1000);34driver.findElement(By.name('q')).sendKeys('webdriver');35driver.findElement(By.name('btnG')).click();36driver.wait(until.titleIs('webdriver - Google Search'), 1000);37driver.findElement(By.name('q')).sendKeys('webdriver');38driver.findElement(By.name('btnG')).click();39driver.wait(until.titleIs('webdriver - Google Search'), 1000);40driver.findElement(By.name('q')).sendKeys('webdriver');41driver.findElement(By.name('btnG')).click();42driver.wait(until.titleIs('webdriver - Google Search'), 1000);

Full Screen

Using AI Code Generation

copy

Full Screen

1const d = new BaseDriver();2const el = d.findElement('some locator');3const els = d.findElementsFromElement(el, 'some locator');4const d = new AndroidDriver();5const el = d.findElement('some locator');6const els = d.findElementsFromElement(el, 'some locator');7const d = new IOSDriver();8const el = d.findElement('some locator');9const els = d.findElementsFromElement(el, 'some locator');10const d = new WindowsDriver();11const el = d.findElement('some locator');12const els = d.findElementsFromElement(el, 'some locator');13const d = new MacDriver();14const el = d.findElement('some locator');15const els = d.findElementsFromElement(el, 'some locator');16const d = new YouiEngineDriver();17const el = d.findElement('some locator');18const els = d.findElementsFromElement(el, 'some locator');19const d = new EspressoDriver();20const el = d.findElement('some locator');21const els = d.findElementsFromElement(el, 'some locator');22const d = new UiAutomator2Driver();23const el = d.findElement('some locator');24const els = d.findElementsFromElement(el, 'some locator');25const d = new XCUITestDriver();26const el = d.findElement('some locator');27const els = d.findElementsFromElement(el, 'some locator');28const d = new WindowsDriver();29const el = d.findElement('some locator');30const els = d.findElementsFromElement(el, 'some locator');31const d = new FakeDriver();32const el = d.findElement('some locator');

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3 .withCapabilities({'browserName': 'chrome'})4 .build();5driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');6driver.findElement(webdriver.By.name('btnG')).click();7driver.wait(function() {8 return driver.getTitle().then(function(title) {9 return title === 'webdriver - Google Search';10 });11}, 1000);12driver.findElements(webdriver.By.css('div')).then(function(elements) {13 console.log('Found ' + elements.length + ' elements.');14 elements[0].findElements(webdriver.By.css('div')).then(function(elements) {15 console.log('Found ' + elements.length + ' elements.');16 });17});18driver.quit();19var webdriver = require('selenium-webdriver');20var driver = new webdriver.Builder()21 .withCapabilities({'browserName': 'chrome'})22 .build();23driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');24driver.findElement(webdriver.By.name('btnG')).click();25driver.wait(function() {26 return driver.getTitle().then(function(title) {27 return title === 'webdriver - Google Search';28 });29}, 1000);30driver.findElements(webdriver.By.css('div')).then(function(elements) {31 console.log('Found ' + elements.length + ' elements.');

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Base Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful