How to use driver.elementsById method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

test.js

Source:test.js Github

copy

Full Screen

...67        await action.perform();68        await action.perform();69        await action.perform();70        await action.perform();71        const list = await driver.elementsById("android:id/text1");72        await list[1].click();73    }else if(type == 2){ // set age less than 1874        await click('android:id/date_picker_header_year');75        let action = new wd.TouchAction(driver);76        action.press({77                    x: anchor,78                    y: startPoint79                });80        action.wait({ms: 10});81        action.moveTo({82                    x: anchor,83                    y:endPoint 84                });85        action.wait({ms: 10});86        action.release();87        await action.perform();88        const list = await driver.elementsById("android:id/text1");89        await list[1].click();90    }else{ // set age negative91        await click('android:id/date_picker_header_year');92        let action = new wd.TouchAction(driver);93        action.press({94                    x: anchor,95                    y: startPoint96                });97        action.wait({ms: 10});98        action.moveTo({99                    x: anchor,100                    y: height-endPoint 101                });102        action.wait({ms: 10});103        action.release();104        await action.perform();105        await action.perform();106        const list = await driver.elementsById("android:id/text1");107        await list[1].click();108    }109    await sleep(500);110    await click("android:id/button1");111    await sleep(500);112}113async function getDate(){114    const date = await driver.elementById('com.example.covidsurvey:id/birthdateText');115    return date.text();116}117async function setCity(){118    await click("com.example.covidsurvey:id/selectedCity");119    await sleep(1000);120    const list = await driver.elementsById("android:id/text1");121    await list[2].click();122    await sleep(500);123}124async function getCity(){125    return (await driver.elementByXPath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.view.ViewGroup/android.widget.FrameLayout[2]/android.widget.ScrollView/android.view.ViewGroup/android.widget.Spinner[1]/android.widget.TextView")).text();126}127async function setGender(type){128    if(type == 0){129        await click("com.example.covidsurvey:id/maleButton");130    }else if(type == 1){131        await click("com.example.covidsurvey:id/femaleButton");132    }else{133        await click("com.example.covidsurvey:id/otherButton");134    }135    await sleep(500);136}137async function getGender(){138    let maleButton = await driver.elementById("com.example.covidsurvey:id/maleButton");139    let femaleButton = await driver.elementById("com.example.covidsurvey:id/femaleButton");140    let otherButton = await driver.elementById("com.example.covidsurvey:id/otherButton");141    if(await maleButton.getAttribute("checked")){142        return 0;143    }else if(await femaleButton.getAttribute("checked")){144        return 1;145    }else if(await otherButton.getAttribute("checked")){146        return 2;147    }else{148        return -1;149    }150}151async function setVaccine(){152    await click("com.example.covidsurvey:id/selectedVaccine");153    await sleep(1000);154    const list = await driver.elementsById("android:id/text1");155    await list[2].click();156    await sleep(500);157}158async function getVaccine(){159    return (await driver.elementByXPath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.view.ViewGroup/android.widget.FrameLayout[2]/android.widget.ScrollView/android.view.ViewGroup/android.widget.Spinner[2]/android.widget.TextView")).text();160}161async function setSideEffect(sideEffect){162    const sideEffectText = await driver.elementById('com.example.covidsurvey:id/sideText');163    await sideEffectText.sendKeys(sideEffect);164    await sleep(500);165}166async function getSideEffect(){167    const sideEffectText = await driver.elementById('com.example.covidsurvey:id/sideText');168    return sideEffectText.text();...

Full Screen

Full Screen

basics-specs.js

Source:basics-specs.js Github

copy

Full Screen

1"use strict";2var env = require('../../../../helpers/env')3  , ADB = require('appium-adb')4  , setup = require("../../../common/setup-base")5  , desired = require("../desired")6  , reset = require("../reset")7  , atv = 'android.widget.TextView';8describe("apidemo - find - basics", function () {9  var driver;10  var apiLevel = "0";11  var singleResourceId = "home";12  setup(this, desired).then(function (d) { driver = d; });13  before(function (done) {14    var adb = new ADB({});15    // the app behaves differently on different api levels when it comes to16    // which resource ids are available for testing, so we switch here to make17    // sure we're using the right resource id below18    adb.getApiLevel(function (err, level) {19      if (err) return done(err);20      apiLevel = level;21      if (apiLevel >= "21") {22        singleResourceId = "decor_content_parent";23      }24      done();25    });26  });27  if (env.FAST_TESTS) {28    beforeEach(function () {29      return reset(driver);30    });31  }32  it('should find a single element by content-description', function (done) {33    driver34      .elementByName("Animation").text().should.become("Animation")35      .nodeify(done);36  });37  it('should find an element by class name', function (done) {38    driver39      .elementByClassName("android.widget.TextView").text().should.become("API Demos")40      .nodeify(done);41  });42  it('should find multiple elements by class name', function (done) {43    driver44      .elementsByClassName("android.widget.TextView")45        .should.eventually.have.length.at.least(10)46      .nodeify(done);47  });48  it('should not find an element that doesnt exist', function (done) {49    driver50      .elementByClassName("blargimarg").should.be.rejectedWith(/status: 7/)51      .nodeify(done);52  });53  it('should not find multiple elements that doesnt exist', function (done) {54    driver55      .elementsByClassName("blargimarg").should.eventually.have.length(0)56      .nodeify(done);57  });58  it('should fail on empty locator', function (done) {59    driver.elementsByClassName("")60      .catch(function (err) { throw err.data; }).should.be.rejectedWith(/selector/)61      .elementsByClassName(atv).should.eventually.exist62      .nodeify(done);63  });64  // TODO: The new version of ApiDemo doesn't use id, find a better example.65  it('should find a single element by id @skip-android-all', function (done) {66    driver67      .complexFind(["scroll", [[3, "views"]], [[7, "views"]]]).click()68      .elementByXPath("//android.widget.TextView[@text='Buttons']").click()69      .elementById("buttons_1_normal").text().should.become("Normal")70      .nodeify(done);71  });72  // TODO: The new version of ApiDemo doesn't use id, find a better example.73  it('should find a single element by string id @skip-android-all', function (done) {74    driver75      .elementById("activity_sample_code").text().should.become("API Demos")76      .nodeify(done);77  });78  it('should find a single element by resource-id', function (done) {79    driver80      .elementById('android:id/' + singleResourceId).should.eventually.exist81      .nodeify(done);82  });83  it('should find multiple elements by resource-id', function (done) {84    driver85      .elementsById('android:id/text1')86        .should.eventually.have.length.at.least(10)87      .nodeify(done);88  });89  it('should find multiple elements by resource-id even when theres just one', function (done) {90    driver91      .elementsById('android:id/' + singleResourceId)92      .then(function (els) {93        els.length.should.equal(1);94      })95      .nodeify(done);96  });97  it('should find a single element by resource-id with implicit package', function (done) {98    driver99      .elementById(singleResourceId).should.eventually.exist100      .nodeify(done);101  });102  it('should find multiple elements by resource-id with implicit package', function (done) {103    driver104      .elementsById('text1')105        .should.eventually.have.length.at.least(10)106      .nodeify(done);107  });108  it('should find multiple elements by resource-id  with implicit package even when theres just one', function (done) {109    driver110      .elementsById(singleResourceId)111      .then(function (els) {112        els.length.should.equal(1);113      })114      .nodeify(done);115  });...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...56    assert.equal(searchParametersElement.length, 1);57  });58  it('should find elements by ID', async function () {59    // Look for element by ID. In Android this is the 'resource-id'60    const actionBarContainerElements = await driver.elementsById('android:id/action_bar_container');61    assert.equal(actionBarContainerElements.length, 1);62  });63  it('should find elements by class name', async function () {64    // Look for elements by the class name. In Android this is the Java Class Name of the view.65    const linearLayoutElements = await driver.elementsByClassName('android.widget.FrameLayout');66    assert.isAbove(linearLayoutElements.length, 1);67  });68  it('should find elements by XPath', async function () {69    // Find elements by XPath70    const linearLayoutElements = await driver.elementsByXPath(`//*[@class='android.widget.FrameLayout']`);71    assert.isAbove(linearLayoutElements.length, 1);72  });...

Full Screen

Full Screen

find-basic-e2e-specs.js

Source:find-basic-e2e-specs.js Github

copy

Full Screen

...37    await driver.elementById(`android:id/${singleResourceId}`)38      .should.eventually.exist;39  });40  it('should find multiple elements by resource-id', async function () {41    await driver.elementsById('android:id/text1')42      .should.eventually.have.length.above(1);43  });44  it('should find multiple elements by resource-id even when theres just one', async function () {45    await driver.elementsById(`android:id/${singleResourceId}`)46      .should.eventually.have.length(1);47  });48  describe('implicit wait', function () {49    let implicitWaitTimeout = 5000;50    before(async function () {51      await driver.setImplicitWaitTimeout(implicitWaitTimeout);52    });53    it('should respect implicit wait with multiple elements', async function () {54      let beforeMs = Date.now();55      await driver.elementsById('there_is_nothing_called_this')56        .should.eventually.have.length(0);57      let afterMs = Date.now();58      (afterMs - beforeMs).should.be.below(implicitWaitTimeout * 2);59    });60  });...

Full Screen

Full Screen

geo-location-e2e-specs.js

Source:geo-location-e2e-specs.js Github

copy

Full Screen

...18    return Math.floor(Math.random() * (max - min + 1) + min);19  }20  it('should set geo location', async function () {21    // If we hit the permission screen, click the 'Continue Button' (sdk >= 28)22    const continueButtons = await driver.elementsById('com.android.permissioncontroller:id/continue_button');23    if (continueButtons.length > 0) {24      await continueButtons[0].click();25    }26    // Get rid of the modal window saying that the app was built for an old version27    await B.delay(1000);28    const okButtons = await driver.elementsById('android:id/button1');29    if (okButtons.length > 0) {30      await okButtons[0].click();31    }32    // Get the text in the app that tells us the latitude and logitude33    const getText = async function () {34      return await retryInterval(10, 1000, async function () {35        const textViews = await driver.elementsByClassName('android.widget.TextView');36        textViews.length.should.be.at.least(2);37        return await textViews[1].text();38      });39    };40    const latitude = getRandomInt(-90, 90);41    const longitude = getRandomInt(-180, 180);42    let text = await getText();...

Full Screen

Full Screen

android-selectors.test.js

Source:android-selectors.test.js Github

copy

Full Screen

...30//   });31//32//   it('should find elements by ID', async function () {33//     // Look for element by ID. In Android this is the 'resource-id'34//     const actionBarContainerElements = await driver.elementsById('android:id/action_bar_container');35//     assert.equal(actionBarContainerElements.length, 1);36//   });37//38//   it('should find elements by class name', async function () {39//     // Look for elements by the class name. In Android this is the Java Class Name of the view.40//     const linearLayoutElements = await driver.elementsByClassName('android.widget.FrameLayout');41//     assert.isAbove(linearLayoutElements.length, 1);42//   });43//44//   it('should find elements by XPath', async function () {45//     // Find elements by XPath46//     const linearLayoutElements = await driver.elementsByXPath(`//*[@class='android.widget.FrameLayout']`);47//     assert.isAbove(linearLayoutElements.length, 1);48//   });...

Full Screen

Full Screen

BasePage.js

Source:BasePage.js Github

copy

Full Screen

...10    this.navDrawer = new NavDrawer(this.driver)11  }12  get searchButton () { return this.driver.elementById('ru.myshows.activity:id/action_search')}13  get searchField () { return this.driver.elementById('ru.myshows.activity:id/search_src_text')}14  get searchResults () { return this.driver.elementsById('ru.myshows.activity:id/show_name')}15  //todo: do smt 16  get backButton () { return this.driver.elementByAccessibilityId('Navigate up')}17  get collapseButton () { return this.driver.elementByAccessibilityId('Collapse')}18  async isLoggedIn () {19    await this.driver.sleep(3000)20    return this.navDrawer.navigationDrawerButton.isDisplayed()21  }22  async searchShow (series) {23    await this.searchButton.click()24    await this.searchField.sendKeys(series)25    await this.driver.waitFor(dHelper.keyboardIsShown, 3000, 500)26    // tap the search button on mobile keyboard27    await this.driver.tap({x: 992, y: 1698})28    await this.driver.sleep(1000)...

Full Screen

Full Screen

by-id-e2e-specs.js

Source:by-id-e2e-specs.js Github

copy

Full Screen

...16    await driver.elementById('android:id/text1').should.eventually.exist;17  });18  it('should return an array of one element if the `multi` param is true', async function () {19    // TODO: this returns an object instead of an array. Investigate.20    let els = await driver.elementsById('android:id/text1');21    els.should.be.an.instanceof(Array);22    els.should.have.length.above(1);23  });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3    .withCapabilities({4    })5    .build();6    .elementsById('button')7    .then(function (el) {8        console.log(el);9    });

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriverio = require('webdriverio');2var options = {3    desiredCapabilities: {4    }5};6var client = webdriverio.remote(options);7    .init()8    .elementsById('element_id')9    .then(function(elements) {10        console.log(elements);11    })12    .end();13var webdriverio = require('webdriverio');14var options = {15    desiredCapabilities: {16    }17};18var client = webdriverio.remote(options);19    .init()20    .elementsByAccessibilityId('element_accessibility_id')21    .then(function(elements) {22        console.log(elements);23    })24    .end();25var webdriverio = require('webdriverio');26var options = {27    desiredCapabilities: {28    }29};30var client = webdriverio.remote(options);31    .init()32    .then(function(elements) {33        console.log(elements);34    })35    .end();36var webdriverio = require('webdriverio');37var options = {38    desiredCapabilities: {39    }40};41var client = webdriverio.remote(options);42    .init()43    .elementsByClassName('XCUIElementTypeWindow')44    .then(function(elements) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var desired = require('./desired');4describe('test', function() {5  this.timeout(300000);6  var driver;7  before(function() {8    driver = wd.promiseChainRemote('localhost', 4723);9    return driver.init(desired);10  });11  after(function() {12    return driver.quit();13  });14  it('should get text of elements found by their accessibility ids', function() {15    return driver.elementsById('IntegerA')16      .then(function(elements) {17        return elements[0].getText()18          .then(function(text) {19            console.log(text);20          });21      });22  });23});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var config = require('./config');4var driver = wd.promiseChainRemote(config.serverConfig);5driver.on('status', function(info) {6  console.log('\x1b[36m%s\x1b[0m', info);7});8driver.on('command', function(meth, path, data) {9  console.log(' > \x1b[33m%s\x1b[0m: %s', meth, path, data || '');10});11driver.on('http', function(meth, path, data) {12  console.log(' > \x1b[90m%s\x1b[0m %s', meth, path, data || '');13});14  .init(config.desiredCapabilities)15  .setImplicitWaitTimeout(5000)16  .elementsById('TextField1')17  .then(function(elements) {18    console.log('Found ' + elements.length + ' elements');19    for (var i = 0; i < elements.length; i++) {20      console.log('Element ' + i + ':');21      console.log(elements[i]);22    }23  })24  .fin(function() { return driver.quit(); })25  .done();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var desiredCaps = {3};4driver.init(desiredCaps)5  .then(function() {6    return driver.elementsById('helloWorldLabel');7  })8  .then(function(elements) {9    return elements[0].getText();10  })11  .then(function(text) {12    if (text.indexOf('hello') > -1) {13      console.log('Test passed');14    } else {15      console.log('Test failed');16    }17  })18  .fin(function() {19    driver.quit();20  })21  .done();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('appium-xcuitest-driver');2var driver = wd.promiseChainRemote();3driver.init({4}).then(function () {5  return driver.elementsById('myButton');6}).then(function (els) {7  console.log(els.length);8}).fin(function () {9  return driver.quit();10}).done();

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