Best JavaScript code snippet using appium-android-driver
find-specs.js
Source:find-specs.js  
...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        const els = await driver.findElements('xpath', '//UIATableCell//UIAButton');268        const texts = await B.all(_.map(els, (el) => 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);...calc-app-1-specs.js
Source:calc-app-1-specs.js  
...80    try {81      let button = (await driver.findElements('class name', 'UIAButton'))[1];82      await driver.click(button);83      let alert = await driver.findElement('class name', 'UIAAlert');84      let els = await driver.findElementsFromElement('class name', 'UIAStaticText', alert);85      let texts = [];86      for (let el of els) {87        texts.push(await driver.getText(el));88      }89      texts.should.include('Cool title');90      texts.should.include('this alert is so cool.');91    } finally {92      await driver.postDismissAlert();93    }94  });95  it('should get tag names of elements', async function () {96    let el = await driver.findElement('class name', 'UIAButton');97    (await driver.getName(el)).should.equal('UIAButton');98    el = await driver.findElement('class name', 'UIAStaticText');...utils.js
Source:utils.js  
...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...find-e2e-specs.js
Source:find-e2e-specs.js  
...65  });66  it('should find subelements', async function () {67    const el = await driver.findElement('xpath', '//document-web');68    el.should.exist;69    const subEls = await driver.findElementsFromElement(el.ELEMENT, 'xpath', '//image[@name="Ubuntu Logo"]');70    subEls.length.should.eql(1);71    await driver.getElementAttribute(subEls[0].ELEMENT, 'tag').should.eventually.eql('img');72  });...from-el-e2e-specs.js
Source:from-el-e2e-specs.js  
...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  });...Using AI Code Generation
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('btnK')).click();9driver.wait(until.titleIs('webdriver - Google Search'), 1000);10driver.quit();11driver.findElement(By.name('q')).sendKeys('webdriver');12driver.findElement(By.name('btnK')).click();13driver.wait(until.titleIs('webdriver - Google Search'), 1000);14driver.quit();15capabilities.setCapability("app", "com.myapp.android");16capabilities.setCapability("appPackage", "com.myapp.android");17capabilities.setCapability("appActivity", "com.myapp.android.MainActivity");18capabilities.setCapability("platformName", "Android");19capabilities.setCapability("platformVersion", "8.0.0");20capabilities.setCapability("deviceName", "Android");21capabilities.setCapability("udid", "emulator-5554");22capabilities.setCapability("autoGrantPermissions", true);23capabilities.setCapability("noReset", true);24capabilities.setCapability("fullReset", false);25capabilities.setCapability("automationName", "UiAutomator2");26capabilities.setCapability("app", "C:/Users/Administrator/Desktop/Android/myapp.apk");27capabilities.setCapability("appPackage", "com.myapp.android");28capabilities.setCapability("appActivity", "com.myapp.android.MainActivity");29capabilities.setCapability("platformName", "Android");30capabilities.setCapability("platformVersion", "8.0.0");31capabilities.setCapability("deviceName", "Android");32capabilities.setCapability("udid", "emulator-5554");33capabilities.setCapability("autoGrantPermissions", true);34capabilities.setCapability("noReset", true);35capabilities.setCapability("fullReset", false);36capabilities.setCapability("automationName", "UiAutomator2");Using AI Code Generation
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.quit();11var webdriver = require('selenium-webdriver');12var By = webdriver.By;13var until = webdriver.until;14var driver = new webdriver.Builder()15    .forBrowser('chrome')16    .build();17driver.findElement(By.name('q')).sendKeys('webdriver');18driver.findElement(By.name('btnG')).click();19driver.wait(until.titleIs('webdriver - Google Search'), 1000);20driver.quit();21var webdriver = require('selenium-webdriver');22var By = webdriver.By;23var until = webdriver.until;24var driver = new webdriver.Builder()25    .forBrowser('chrome')26    .build();27driver.findElement(By.name('q')).sendKeys('webdriver');28driver.findElement(By.name('btnG')).click();29driver.wait(until.titleIs('webdriver - Google Search'), 1000);30driver.quit();31var webdriver = require('selenium-webdriver');32var By = webdriver.By;33var until = webdriver.until;34var driver = new webdriver.Builder()35    .forBrowser('chrome')36    .build();37driver.findElement(By.name('q')).sendKeys('webdriver');38driver.findElement(By.name('btnG')).click();39driver.wait(until.titleIs('webdriver - Google Search'), 1000);40driver.quit();41var webdriver = require('selenium-webdriver');42var By = webdriver.By;43var until = webdriver.until;44var driver = new webdriver.Builder()45    .forBrowser('chrome')46    .build();47driver.findElement(By.name('q')).sendKeys('webdriver');Using AI Code Generation
1const webdriverio = require('webdriverio');2const options = {3  capabilities: {4  },5};6const client = webdriverio.remote(options);7  .init()8  .then(() => {9      .elementByAccessibilityId('edittext')10      .then((element) => {11          .findElementsFromElement(element, 'class name', 'android.widget.EditText')12          .then((elements) => {13            console.log('Number of elements found: ' + elements.length);14          });15      });16  })17  .catch((error) => {18    console.log(error);19  });20from appium import webdriver21caps = {22}23element = driver.find_element_by_accessibility_id('edittext')24elements = driver.find_elements_from_element(element, 'class name', 'android.widget.EditText')25print('Number of elements found: ' + len(elements))26driver.quit()27caps = {28}29driver = Appium::Driver.new({Using AI Code Generation
1const wdio = require("webdriverio");2const opts = {3    capabilities: {4    }5};6async function main() {7    const client = await wdio.remote(opts);8    const elements = await client.findElementsFromElement("android.widget.LinearLayout", "android.widget.TextView");9    console.log(elements);10    await client.deleteSession();11}12main();13const wdio = require("webdriverio");14const opts = {15    capabilities: {16    }17};18async function main() {19    const client = await wdio.remote(opts);20    const elements = await client.findElementsFromElement("XCUIElementTypeCell", "XCUIElementTypeStaticText");21    console.log(elements);22    await client.deleteSession();23}24main();25const wdio = require("webdriverio");26const opts = {27    capabilities: {28    }29};30async function main() {31    const client = await wdio.remote(opts);32    const parentElement = await client.findElement("android.widget.LinearLayout");Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var path = require('path');4var desired = {5  app: path.resolve(__dirname, 'selendroid-test-app-0.11.0.apk')6};7var browser = wd.promiseChainRemote("Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var colors = require('colors');4var desiredCaps = {5};6var driver = wd.promiseChainRemote('localhost', 4723);7  .init(desiredCaps)8  .elementById('io.appium.android.apis:id/content')9  .then(function(element) {10      .then(function(elements) {11        console.log('Number of WebView elements: '.blue, elements.length);12        assert.ok(elements.length > 0);13      });14  })15  .fin(function() { return driver.quit(); })16  .done();17var wd = require('wd');18var assert = require('assert');19var colors = require('colors');20var desiredCaps = {21};22var driver = wd.promiseChainRemote('localhost', 4723Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desired = {4};5var driver = wd.remote("localhost", 4723);6driver.init(desired).then(function() {7  return driver.elementById("android:id/list");8}).then(function(el) {9  return driver.findElementsFromElement(el.ELEMENT, "-android uiautomator", "new UiSelector().clickable(true)");10}).then(function(els) {11  console.log("Number of elements found: " + els.length);12  for(var i = 0; i < els.length; i++) {13    driver.elementIdText(els[i].ELEMENT).then(function(text) {14      console.log("Element " + i + " text: " + text);15    });16  }17}).fin(function() { return driver.quit(); })18  .done();Using AI Code Generation
1var webdriver = require('selenium-webdriver'),2    until = webdriver.until;3var desiredCaps = {4};5var driver = new webdriver.Builder()6    .withCapabilities(desiredCaps)7    .build();8driver.getSession().then(function(session) {9  console.log('Session ID: ' + session.id_);10  console.log('Caps: ' + JSON.stringify(session.caps_));11});12driver.findElement(By.id('android:id/text1')).click();13driver.findElement(By.className('android.webkit.WebView')).then(function(webview) {14  driver.findElementsFromElement(webview, By.className('android.widget.Button')).then(function(buttons) {15    console.log('There are ' + buttons.length + ' buttons on the page');16  });17});18driver.quit();19var webdriver = require('selenium-webdriver'),20    until = webdriver.until;21var desiredCaps = {22};Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
