How to use driver.getElementRect method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

element-specs.js

Source:element-specs.js Github

copy

Full Screen

...254      }255    });256    it('should get element rect in native context', async function () {257      isWebContextStub = sinon.stub(driver, 'isWebContext').returns(false);258      const rect = await driver.getElementRect(elem);259      isWebContextStub.calledOnce.should.be.true;260      getNativeRectStub.calledOnce.should.be.true;261      getLocationStub.calledOnce.should.be.false;262      getSizeStub.calledOnce.should.be.false;263      rect.x.should.eql(0);264      rect.y.should.eql(50);265      rect.width.should.eql(100);266      rect.height.should.eql(200);267    });268    it('should get element rect in Web context', async function () {269      isWebContextStub = sinon.stub(driver, 'isWebContext').returns(true);270      const rect = await driver.getElementRect(elem);271      isWebContextStub.calledOnce.should.be.true;272      getNativeRectStub.calledOnce.should.be.false;273      getLocationStub.calledOnce.should.be.true;274      getSizeStub.calledOnce.should.be.true;275      rect.x.should.eql(0);276      rect.y.should.eql(50);277      rect.width.should.eql(100);278      rect.height.should.eql(200);279    });280  });...

Full Screen

Full Screen

Gestures.js

Source:Gestures.js Github

copy

Full Screen

...176	 * @param {Element} dropZoneElement177	 */178	static dragAndDrop(draggableElement, dropZoneElement) {179		// Get the dropzone and the draggable element rectangles180		const dropZoneRec = driver.getElementRect(dropZoneElement.elementId);181		const dragElementRec = driver.getElementRect(draggableElement.elementId);182		// See http://appium.io/docs/en/commands/interactions/actions/#actions183		driver.performActions([ {184			type: 'pointer',185			id: 'finger1',186			parameters: { pointerType: 'touch' },187			actions: [188				// Pick the center of the draggable element189				{190					type: 'pointerMove',191					duration: 0,192					x: dragElementRec.x + dragElementRec.width / 2,193					y: dragElementRec.y + dragElementRec.height / 2,194				},195				{ type: 'pointerDown', button: 0 },196				{ type: 'pause', duration: 250 },197				// Finger moves a small amount very quickly to trigger the event198				{199					type: 'pointerMove',200					duration: 1,201					x: dragElementRec.x + dragElementRec.width / 2,202					y: dragElementRec.y + dragElementRec.height / 2 - 10,203				},204				{ type: 'pause', duration: 100 },205				// Move it to the center of the drop zone206				{207					type: 'pointerMove',208					duration: 250,209					x: dropZoneRec.x + dropZoneRec.width / 2,210					y: dropZoneRec.y + dropZoneRec.height / 2,211				},212				{ type: 'pointerUp', button: 0 },213			],214		} ]);215	}216	/**217	 * Pinch or zoom an element (pinch doesn't work on Android with this method yet)218	 *219	 * @param {Element} element220	 * @param {string} gesture Possible values are `zoom|pinch`221	 */222	static pinchAndZoom(element, gesture = 'zoom') {223		const isZoom = gesture.toLowerCase() === 'zoom';224		const { x, y, width, height } = driver.getElementRect(element.elementId);225		const centerX = x + width / 2;226		const centerY = y + height / 2;227		// iOS seems to respond 'heavier' on a position change, so make it way smaller228		const xPosition = driver.isIOS ? 10 : width / 2;229		const finger1 = {230			start: { type: 'pointerMove', duration: 0, x: centerX, y: centerY },231			end: { type: 'pointerMove', duration: 250, x: centerX - xPosition, y: centerY },232		};233		const finger2 = {234			start: { type: 'pointerMove', duration: 0, x: centerX, y: centerY },235			end: { type: 'pointerMove', duration: 250, x: centerX + xPosition, y: centerY },236		};237		driver.performActions([238			// First finger239			{240				type: 'pointer',241				id: 'finger1',242				parameters: { pointerType: 'touch' },243				actions: [244					// move finger into start position245					isZoom ? finger1.start : finger1.end,246					// finger comes down into contact with screen247					{ type: 'pointerDown', button: 0 },248					// pause for a little bit249					{ type: 'pause', duration: 100 },250					// finger moves to end position251					isZoom ? finger1.end : finger1.start,252					// finger lets up, off the screen253					{ type: 'pointerUp', button: 0 },254				],255			},256			// Second finger257			{258				type: 'pointer',259				id: 'finger2',260				parameters: { pointerType: 'touch' },261				actions: [262					// move finger into start position263					isZoom ? finger2.start : finger2.end,264					// finger comes down into contact with screen265					{ type: 'pointerDown', button: 0 },266					// pause for a little bit267					{ type: 'pause', duration: 100 },268					// finger moves to end position269					isZoom ? finger2.end : finger2.start,270					// finger lets up, off the screen271					{ type: 'pointerUp', button: 0 },272				],273			},274		]);275	}276	/**277	 * Pinch or zoom an element (pinch doesn't work on Android with this method yet)278	 *279	 * @param {Element} element280	 */281	static swipeItemLeft(element) {282		const { x, y, width, height } = driver.getElementRect(element.elementId);283		const centerX = x + width / 2;284		const centerY = y + height / 2;285		driver.performActions([286			{287				type: 'pointer',288				id: 'finger1',289				parameters: { pointerType: 'touch' },290				actions: [291					// move finger into start position292					{ type: 'pointerMove', duration: 0, x: centerX, y: centerY },293					// finger comes down into contact with screen294					{ type: 'pointerDown', button: 0 },295					// pause for a little bit296					{ type: 'pause', duration: 100 },...

Full Screen

Full Screen

rectangles.test.js

Source:rectangles.test.js Github

copy

Full Screen

1import * as DeviceInfo from '../../lib/methods/getDeviceInfo'2import {IMAGE_STRING} from '../mocks/mocks'3describe('rectangles', () => {4    let getDeviceInfoSpy, ignoreRectanglesOptions, Rectangles5    beforeEach(() => {6        jest.isolateModules(() => {7            Rectangles = require('../../lib/methods/rectangles')8        })9        delete global.driver10        delete global.$$11        global.$$ = () => [{'element-selector-1': {}}]12        global.driver = {13            capabilities: {},14            getElementRect: jest.fn().mockResolvedValue({x: 1, y: 2, width: 10, height: 20}),15            getSettings: jest.fn().mockResolvedValue({allowInvisibleElements: false}),16            updateSettings: jest.fn().mockResolvedValue({}),17            isIOS: false,18            isAndroid: false,19        }20        getDeviceInfoSpy = jest.spyOn(DeviceInfo, 'getDeviceInfo').mockResolvedValue({21            dpr: 2,22            isIphoneXSeries: true,23            isLargeIphoneXSeries: false,24            screenSize: {25                height: 1700,26                width: 812,27            },28            screenshotHeight: 1700,29            screenshotWidth: 812,30            isPortrait: true,31            rectangles: {32                androidNavigationBar: {33                    bottom: 800,34                    top: 760,35                    left: 0,36                    right: 400,37                },38                iOSHomeBar: {39                    bottom: 5,40                    top: 883,41                    left: 133,42                    right: 148,43                },44                statusBar: {45                    bottom: 26,46                    top: 0,47                    left: 0,48                    right: 812,49                },50            },51        })52        ignoreRectanglesOptions = {53            blockOuts: [],54            blockOutNavigationBar: false,55            blockOutStatusBar: false,56            elementBlockOuts: [],57        }58    })59    afterEach(() => {60        global.driver = {61            getElementRect: jest.fn().mockRestore(),62            getSettings: jest.fn().mockRestore(),63            updateSettings: jest.fn().mockRestore(),64        }65        getDeviceInfoSpy.mockRestore()66    })67    describe('determineIgnoreRectangles', () => {68        it('should return nothing if no ignore rectangles need to be returned', async () => {69            expect(await Rectangles.determineIgnoreRectangles(IMAGE_STRING, ignoreRectanglesOptions)).toMatchSnapshot()70        })71        it('should get the status bar block outs', async () => {72            ignoreRectanglesOptions.blockOutStatusBar = true73            expect(await Rectangles.determineIgnoreRectangles(IMAGE_STRING, ignoreRectanglesOptions)).toMatchSnapshot()74        })75        it('should get the android navigation bar block outs', async () => {76            global.driver.isAndroid = true77            ignoreRectanglesOptions.blockOutNavigationBar = true78            expect(await Rectangles.determineIgnoreRectangles(IMAGE_STRING, ignoreRectanglesOptions)).toMatchSnapshot()79        })80        it('should get the block outs', async () => {81            ignoreRectanglesOptions.blockOuts = [{x: 11, y: 22, width: 33, height: 44}, {82                x: 21,83                y: 32,84                width: 43,85                height: 5486            }]87            expect(await Rectangles.determineIgnoreRectangles(IMAGE_STRING, ignoreRectanglesOptions)).toMatchSnapshot()88        })89        it('should return iPhone X bottom bar rectangles', async () => {90            ignoreRectanglesOptions.blockOutIphoneXBottomBar = true91            global.driver.isIOS = true92            expect(await Rectangles.determineIgnoreRectangles(IMAGE_STRING, ignoreRectanglesOptions)).toMatchSnapshot()93        })94        it('should call the settings API for android when elements needs to be blocked out', async () => {95            global.driver.isAndroid = true96            ignoreRectanglesOptions.elementBlockOuts = [{element: {selector: 'selector-1'}}, {97                element: {selector: 'selector-1'}98            }]99            await Rectangles.determineIgnoreRectangles(IMAGE_STRING, ignoreRectanglesOptions)100            expect(global.driver.getSettings).toBeCalled()101            expect(global.driver.updateSettings).toBeCalledWith({allowInvisibleElements: true})102            expect(global.driver.updateSettings).toHaveBeenLastCalledWith({allowInvisibleElements: false})103        })104    })105    describe('determineValidBlockOuts', () => {106        it('should return the valid blockouts if an valid array if provided', () => {107            const blockOuts = [108                {x: 1, y: 2, width: 3, height: 4},109                {x: 1, y: 2, width: 3, height: 4},110            ]111            expect(Rectangles.determineValidBlockOuts(blockOuts)).toMatchSnapshot()112        })113        it('should return the valid blockouts if an array with invalid keys is provided', () => {114            const blockOuts = [115                {x: 5, y: 6, width: 7, height: 8},116                {b: 5, y: 6, widthy: 7, height: 8},117                {x: 9, y: 12, width: 13, height: 14},118                {x: 9, ho: 12, width: 13, bar: 14},119            ]120            expect(Rectangles.determineValidBlockOuts(blockOuts)).toMatchSnapshot()121        })122    })123    describe('determineElementBlockOuts', () => {124        it('should return an empty array if no elements are provided', async () => {125            expect(await Rectangles.determineElementBlockOuts({126                components: [],127                dpr: 1,128            })).toMatchSnapshot()129        })130        it('should return an array of one element blockout if 1 element is provided', async () => {131            const selector = 'element-selector-1'132            const components = [133                {element: {selector}}134            ]135            global.$$ = () => [{'element-selector-1': {}}]136            expect(await Rectangles.determineElementBlockOuts({137                components: components,138                dpr: 1,139            })).toMatchSnapshot()140        })141        it('should return an array of one element blockout if multiple elements are provided but 1 with an element number', async () => {142            const selector = 'element-selector-1'143            const components = [144                {element: {selector}, elementNumber: 1}145            ]146            global.$$ = () => [{'element-selector-1': {}}, {'element-selector-1': {}}, {'element-selector-1': {}}]147            expect(await Rectangles.determineElementBlockOuts({148                components: components,149                dpr: 1,150            })).toMatchSnapshot()151        })152        it('should return an array of element blockouts if multiple elements are provided', async () => {153            const selector = 'element-selector-1'154            const components = [{element: {selector}}, {element: {selector}}, {element: {selector}}]155            global.$$ = () => [{'element-selector-1': {}}, {'element-selector-1': {}}, {'element-selector-1': {}}]156            expect(await Rectangles.determineElementBlockOuts({157                components: components,158                dpr: 1,159            })).toMatchSnapshot()160        })161    })162    describe('determineDimensions', () => {163        it('should be able to determine the dimensions when no margin is provided', () => {164            expect(Rectangles.determineDimensions({165                x: 100,166                y: 200,167                width: 1000,168                height: 2000,169            }, 0)).toMatchSnapshot()170        })171        it('should be able to determine the dimensions when a positive margin is provided', () => {172            expect(Rectangles.determineDimensions({173                x: 100,174                y: 200,175                width: 1000,176                height: 2000,177            }, 25)).toMatchSnapshot()178        })179        it('should be able to determine the dimensions when a negative margin is provided', () => {180            expect(Rectangles.determineDimensions({181                x: 100,182                y: 200,183                width: 1000,184                height: 2000,185            }, -25)).toMatchSnapshot()186        })187    })188    describe('getElementRectangles', () => {189        it('should return element rectangles', async () => {190            expect(await Rectangles.getElementRectangles({elementId: 1})).toMatchSnapshot()191            expect(global.driver.getElementRect).toBeCalledWith(1)192        })193    })...

Full Screen

Full Screen

rectangles.js

Source:rectangles.js Github

copy

Full Screen

...151 *      y: number152 * }>}153 */154export async function getElementRectangles(element) {155    return (await (driver.getElementRect(element.elementId)))...

Full Screen

Full Screen

WebElement.js

Source:WebElement.js Github

copy

Full Screen

1'use strict';2const {ArgumentGuard, TypeUtils} = require('@applitools/eyes-sdk-core');3const command = require('../services/selenium/Command');4const {By} = require('../By');5/**6 * Wrapper for Webdriverio element7 */8class WebElement {9  /**10   * @param {WebDriver} driver11   * @param {Object} element - WebElement JSON object12   * @param {By|Object} locator13   */14  constructor(driver, element, locator) {15    ArgumentGuard.notNull(locator, "locator");16    this._driver = driver;17    this._element = element;18    this._locator = locator;19  }20  /**21   * @param {WebDriver} driver22   * @param {By} locator23   * @param {int} [retry]24   * @return {Promise.<WebElement>}25   */26  static async findElement(driver, locator, retry = 0) {27    try {28      const element = await driver.remoteWebDriver.findElement(locator.using, locator.value);29      return new WebElement(driver, element, locator);30    } catch (e) {31      if (retry > 3) {32        throw e;33      } else {34        return WebElement.findElement(driver, locator, retry++);35      }36    }37  }38  /**39   * @todo40   */41  findElements(locator) {42  }43  /**44   * @returns {Promise.<{x, y}>}45   */46  async getLocation() {47    try {48      return await this._driver.remoteWebDriver.getElementRect(this.elementId);49    } catch (e) {50      try {51        return this._driver.remoteWebDriver.getElementLocation(this.elementId);52      } catch (ignored) {53        throw e;54      }55    }56  }57  /**58   * @returns {Promise.<width, height>}59   */60  async getSize() {61    try {62      return await this._driver.remoteWebDriver.getElementRect(this.elementId);63    } catch (e) {64      try {65        return this._driver.remoteWebDriver.getElementSize(this.element.ELEMENT);66      } catch (ignored) {67        throw e;68      }69    }70  }71  /**72   * @returns {Promise.<x, y, width, height>}73   */74  async getRect() {75    // todo need to replace elementIdSize and elementIdLocation to elementIdRect76    const rect = await this._driver.remoteWebDriver.elementIdRect(this.elementId);77    return rect;78  }79  /**80   * @returns {Promise}81   */82  click() {83    return this._driver.remoteWebDriver.elementClick(this.elementId);84  }85  /**86   *87   */88  takeScreenshot(opt_scroll) { // todo89    return this._driver.screenshot(opt_scroll);90    // return this.requestHandler.create(`/session/:sessionId/element/${id}/screenshot`);91  }92  /**93   * @param {object} object94   * @return {boolean}95   */96  static isLocator(object) {97    return (object instanceof By) || TypeUtils.has(object, ['using', 'value']);98  }99  static equals(a, b) {100    if (a == undefined || b == undefined) {101      return false;102    }103    if (!(a instanceof this) || !(b instanceof this)) {104      return false;105    }106    if (a === b) {107      return true;108    }109    const elementA = a.getWebElement().elementId;110    const elementB = b.getWebElement().elementId;111    if (a === b) {112      return true;113    }114    let cmd = new command.Command(command.Name.ELEMENT_EQUALS);115    cmd.setParameter('id', elementA);116    cmd.setParameter('other', elementB);117    return a._driver.executeCommand(cmd).then(r => {118      const {value} = r;119      return value;120    }).catch(e => {121      throw e;122    });123  }124  /**125   * @param keysToSend126   * @returns {Promise}127   */128  sendKeys(keysToSend) {129    const that = this;130    return that._driver.remoteWebDriver.elementIdClick(this.elementId).then(() => {131      return that._driver.remoteWebDriver.keys(keysToSend);132    });133  }134  /**135   * @returns {Promise.<{offsetLeft, offsetTop}>}136   */137  async getElementOffset() {138    const offsetLeft = await this._driver.remoteWebDriver.elementIdAttribute(this.elementId, 'offsetLeft');139    const offsetTop = await this._driver.remoteWebDriver.elementIdAttribute(this.elementId, 'offsetTop');140    return {offsetLeft: parseInt(offsetLeft.value), offsetTop: parseInt(offsetTop.value)};141  }142  /**143   * @returns {Promise.<{scrollLeft, scrollTop}>}144   */145  async getElementScroll() {146    const that = this;147    const scrollLeft = await that._driver.remoteWebDriver.elementIdAttribute(this.elementId, 'scrollLeft');148    const scrollTop = await that._driver.remoteWebDriver.elementIdAttribute(this.elementId, 'scrollTop');149    return {scrollLeft: parseInt(scrollLeft), scrollTop: parseInt(scrollTop.value)};150  }151  /**152   * @returns {EyesWebDriver}153   */154  getDriver() {155    return this._driver;156  }157  /**158   * @return {Object|*}159   */160  get element() {161    return this._element;162  }163  /**164   * @return {string}165   */166  get elementId() {167    return this._element.elementId || this._element.ELEMENT;168  }169  get locator() {170    return this._locator;171  }172  toString() {173    return this._element ? JSON.stringify(this._element) : JSON.stringify(this.locator);174  }175}...

Full Screen

Full Screen

ios-create-web-session.test.js

Source:ios-create-web-session.test.js Github

copy

Full Screen

...37      //     direction: 'down',38      //     precent:2.0,39      //   }40      // )41      // const scrollViewRect = await driver.getElementRect(await driver.$('//a[@class="siteHeader__logo"]'));42      // const centerX = scrollViewRect.x + (scrollViewRect.width / 2);43      // const startY = scrollViewRect.y + (scrollViewRect.height * 0.9);44      // const endY = scrollViewRect.y;45      // for (let scrolls = 0; scrolls < 5; scrolls++) {46      //   await driver.performActions([47      //     {48      //       type: 'pointer',49      //       id: 'finger1',50      //       parameters: {pointerType: 'touch'},51      //       actions: [52      //         {type: 'pointerMove', duration: 0, x: centerX, y: startY},53      //         {type: 'pointerDown', button: 0},54      //         {type: 'pause', duration: 3000},55      //         {type: 'pointerMove', duration: 500, x: centerX, y: endY},...

Full Screen

Full Screen

carousel.js

Source:carousel.js Github

copy

Full Screen

...112     */113    getCarouselRectangles() {114        CAROUSEL_RECTANGLES =115            CAROUSEL_RECTANGLES ||116            driver.getElementRect($(SELECTORS.CAROUSEL).elementId);117        return CAROUSEL_RECTANGLES;118    }119}...

Full Screen

Full Screen

SwipePage.js

Source:SwipePage.js Github

copy

Full Screen

...19  getCarouselRectangles() {20    this.waitForIsDisplayed()21    CAROUSEL_RECTANGLES =22      CAROUSEL_RECTANGLES ||23      driver.getElementRect($(SELECTORS.CAROUSEL).elementId);24    return CAROUSEL_RECTANGLES;25  }26     /**27     * Swipe the carousel to the LEFT (from  right to left)28     */29  swipeLeft() {30    const carouselRectangles = this.getCarouselRectangles();31    const y = Math.round((carouselRectangles.y + carouselRectangles.height) / 2);32    Gestures.swipe(33        { x: Math.round(carouselRectangles.width - (carouselRectangles.width * 0.20)), y },34        { x: Math.round(carouselRectangles.x + (carouselRectangles.width * 0.20)), y },35    );36  }37     /**...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require('webdriverio');2const opts = {3    capabilities: {4    }5};6(async () => {7    const client = await wdio.remote(opts);8    const element = await client.$('XCUIElementTypeButton');9    const location = await element.getElementRect('location');10    const size = await element.getElementRect('size');11    console.log(location);12    console.log(size);13    await client.deleteSession();14})();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('webdriverio');2var assert = require('assert');3var opts = {4  desiredCapabilities: {5  }6};7var client = wd.promiseChainRemote(opts);8  .init()9  .elementByAccessibilityId('7')10  .then(function (el) {11    return client.getElementRect(el.ELEMENT)12  })13  .then(function (rect) {14    console.log(rect);15  })16  .catch(function (err) {17    console.log(err);18  })19  .fin(function () {20      .quit()21      .finally(function () {22        console.log('Done!');23      });24  })25  .done();

Full Screen

Using AI Code Generation

copy

Full Screen

1var driver = new webdriver.Builder()2.forBrowser('safari')3.build();4driver.manage().window().setSize(400, 400);5driver.findElement(webdriver.By.name('q'))6.sendKeys('webdriver')7.then(function(){8    driver.findElement(webdriver.By.name('btnG'))9    .click()10    .then(function(){11        driver.findElement(webdriver.By.name('btnG')).isDisplayed()12        .then(function(){13            driver.findElement(webdriver.By.name('btnG')).getRect()14            .then(function(rect){15                console.log(rect);16            });17        });18    });19});

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require('webdriverio');2const assert = require('assert');3const opts = {4  capabilities: {5  }6};7async function main() {8  let client = await wdio.remote(opts);9  let el = await client.findElement('class name', 'XCUIElementTypeButton');10  let rect = await client.getElementRect(el['ELEMENT']);11  console.log(rect);12  client.deleteSession();13}14main();15{16}

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var asserters = wd.asserters;3var desired = {4};5var driver = wd.promiseChainRemote('localhost', 4723);6driver.init(desired)7  .then(function() {8    return driver.elementByAccessibilityId('myButton');9  })10  .then(function(el) {11    return driver.getElementRect(el);12  })13  .then(function(rect) {14    console.log('location: ' + JSON.stringify(rect));15  })16  .fin(function() { return driver.quit(); })17  .done();

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const assert = require('assert');3const PORT = 4723;4const config = {5};6const driver = wd.promiseChainRemote('localhost', PORT);7(async function example() {8  try {9    await driver.init(config);10    await driver.sleep(10000);11    await driver.setImplicitWaitTimeout(10000);12    let element = await driver.elementByAccessibilityId('Add');13    let elementRect = await driver.getElementRect(element);14    console.log(elementRect);15    await driver.execute('mobile: scroll', {direction: 'up'});16    await driver.sleep(10000);17    elementRect = await driver.getElementRect(element);18    console.log(elementRect);19  } catch (err) {20    console.log(err);21  } finally {22    await driver.quit();23  }24})().catch((err) => {25  console.log(err);26});

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 Xcuitest Driver automation tests on LambdaTest cloud grid

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

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful