Best JavaScript code snippet using appium-xcuitest-driver
GUI.android.test.js
Source:GUI.android.test.js  
...8        let driver = helper.driver;9        await driver.waitForElementByAccessibilityId('mine_MyOrders', 20000)// çå¾
æç订å10            .elementByAccessibilityId('left_text')// è·åæç订åå·¦ä¾§ææ¡;11            .text();12        let leftTexts = await driver.elementsByAccessibilityId('left_text');13        console.log(leftTexts);14        let text = await leftTexts[0].text();15        console.log(text);16        expect(text).toEqual('æçå
¬å¸');17        text = await leftTexts[1].text();18        console.log(text);19        expect(text).toEqual('æç订å');20        text = await leftTexts[2].text();21        console.log(text);22        expect(text).toEqual('æçæ¬å¤´');23        text = await leftTexts[3].text();24        console.log(text);25        expect(text).toEqual('è系客æ');26        text = await leftTexts[4].text();27        console.log(text);28        expect(text).toEqual('å çåä½');29        text = await leftTexts[5].text();30        console.log(text);31        expect(text).toEqual('设置');32        let rightTexts = await driver.elementsByAccessibilityId('right_text');33        console.log(leftTexts);34        text = await rightTexts[0].text();35        console.log(text);36        expect(text).toEqual('3');37        text = await rightTexts[1].text();38        console.log(text);39        expect(text).toEqual('3');40        text = await rightTexts[2].text();41        console.log(text);42        expect(text).toEqual('2');43    });44    it('æçå
¬å¸é¡µæ°æ®æ£æµ', async() => {45        let driver = helper.driver;46        //ç¹å»æçå
¬å¸é¡µé¢...controls.js
Source:controls.js  
...44  }45  while (numClicked < totalButtons) {46    while (somethingLeftToClick && numClicked < totalButtons) {47      somethingLeftToClick = false;48      const buttons = await driver.elementsByAccessibilityId(49        Array.isArray(inputs[question.name])50          ? inputs[question.name][numClicked]51          : inputs[question.name]52      );53      for (const button of buttons) {54        let buttonLocation = await button.getLocation();55        if (56          buttonLocation.y < nextQuestionLocation.y &&57          buttonLocation.y > lastClickedY &&58          buttonLocation.y < deviceInfo.SCREEN_Y59        ) {60          await button.click();61          somethingLeftToClick = true;62          numClicked++;63          lastClickedY = buttonLocation.y;64          break;65        }66      }67    }68    if (numClicked < totalButtons) {69      somethingLeftToClick = true;70      await half_scroll(driver, deviceInfo);71      nextQuestionLocation = await get_element_location(72        driver,73        deviceInfo,74        nextQuestion ? nextQuestion.name : screen_info.button.name75      );76      if (!nextQuestionLocation) {77        nextQuestionLocation = {78          x: deviceInfo.SCREEN_X,79          y: deviceInfo.SCREEN_Y + 1,80        };81      }82      buttons = await driver.elementsByAccessibilityId(83        inputs[question.name][numClicked - 1]84      );85      for (const button of buttons) {86        if ((await button.getAttribute("focused")) == "true") {87          lastClickedY = (await button.getLocation()).y;88          break;89        }90      }91    }92  }93}94//Pick answer for button choice question (ios)95export async function ios_buttonGrid(96  driver,97  question,98  nextQuestion,99  screen_info,100  inputs,101  deviceInfo102) {103  let questionLocation = await get_element_location(104    driver,105    deviceInfo,106    question.name107  );108  let totalButtons = Array.isArray(inputs[question.name])109    ? inputs[question.name].length110    : 1;111  let numClicked = 0;112  let lastClickedY = questionLocation.y;113  let nextQuestionLocation = await get_element_location(114    driver,115    deviceInfo,116    nextQuestion ? nextQuestion.name : screen_info.button.name117  );118  if (!nextQuestionLocation) {119    nextQuestionLocation = {120      x: deviceInfo.SCREEN_X,121      y: deviceInfo.SCREEN_Y + 1,122    };123  }124  while (numClicked < totalButtons) {125    const buttons = await driver.elementsByAccessibilityId(126      Array.isArray(inputs[question.name])127        ? inputs[question.name][numClicked]128        : inputs[question.name]129    );130    var lastButton;131    for (const button of buttons) {132      let buttonLocation = await button.getLocation();133      if (buttonLocation.y > deviceInfo.SCREEN_Y) {134        await full_scroll(driver, deviceInfo);135        buttonLocation = await button.getLocation();136        nextQuestionLocation = await get_element_location(137          driver,138          deviceInfo,139          nextQuestion ? nextQuestion.name : screen_info.button.name140        );141        if (!nextQuestionLocation) {142          nextQuestionLocation = {143            x: deviceInfo.SCREEN_X,144            y: deviceInfo.SCREEN_Y + 1,145          };146        }147        lastClickedY = lastButton ? (await lastButton.getLocation()).y : 0;148      }149      if (150        buttonLocation.y < nextQuestionLocation.y &&151        buttonLocation.y > lastClickedY152      ) {153        await button.click();154        numClicked++;155        lastClickedY = buttonLocation.y;156        lastButton = button;157        break;158      }159    }160  }161}162//Pick answer for select menu question (android)163export async function android_select(driver, question, inputs, deviceInfo) {164  await driver.elementByClassName("android.widget.Spinner").click();165  let foundChoice = false;166  while (!foundChoice) {167    let dropdown_items = await driver.elementsByClassName(168      "android.widget.CheckedTextView"169    );170    for (const item of dropdown_items) {171      const text = await item.text();172      if (text === inputs[question.name]) {173        item.click();174        foundChoice = true;175        break;176      }177    }178    if (!foundChoice) {179      //scroll up to see more choices180      let scroll = new wd.TouchAction(driver)181        .press({182          x: Math.trunc(deviceInfo.SCREEN_X * 0.25),183          y: Math.trunc(deviceInfo.SCREEN_Y * 0.5),184        })185        .wait(2000)186        .moveTo({187          x: Math.trunc(deviceInfo.SCREEN_X * 0.25),188          y: Math.trunc(deviceInfo.SCREEN_Y * 0.9),189        })190        .release();191      await scroll.perform();192    }193  }194}195//Pick answer for select menu question (ios)196export async function ios_select(driver, question, inputs) {197  await driver.elementByAccessibilityId(question.link + " >").click();198  const pickerWheel = await driver.elementByClassName(199    "XCUIElementTypePickerWheel"200  );201  await driver.setImplicitWaitTimeout(100);202  while (!(await driver.hasElementByAccessibilityId(inputs[question.name]))) {203    await driver.execute("mobile: selectPickerWheelValue", {204      element: pickerWheel,205      order: "previous",206      offset: 0.1,207    });208  }209  await driver.elementByAccessibilityId(strings.common.button.done).click();210  await driver.setImplicitWaitTimeout(10000);211}212//Put text into a text entry box213export async function text_entry(driver, deviceInfo, question, inputs) {214  if (question.placeholder) {215    await driver216      .elementByAccessibilityId(question.placeholder)217      .type(inputs[question.placeholder]);218  } else {219    if (deviceInfo.PLATFORM == "iOS") {220      await driver221        .elementByClassName("XCUIElementTypeTextField")222        .type(inputs[question.name]);223    } else {224      await driver.elementByClassName("android.widget.EditText").click();225      await driver226        .elementByClassName("android.widget.EditText")227        .type(inputs[question.name]);228    }229    await driver.hideDeviceKeyboard();230  }231}232//Choose specified checkboxes for checkbox question233export async function choose_checkboxes(driver, deviceInfo, question, inputs) {234  for (const item of question.options) {235    if (inputs[question.name].includes(item)) {236      await scroll_to_element(driver, deviceInfo, item);237      await driver.elementByAccessibilityId(item).click();238    }239  }240}241//Choose specified choice for radio button question242export async function choose_radio(driver, deviceInfo, question, inputs) {243  let questionLocation = await get_element_location(244    driver,245    deviceInfo,246    question.name247  );248  let buttons = await driver.elementsByAccessibilityId(inputs[question.name]);249  for (const button of buttons) {250    let buttonLocation = await button.getLocation();251    if (buttonLocation.y > questionLocation.y) {252      while (buttonLocation.y > deviceInfo.SCREEN_Y) {253        half_scroll(driver, deviceInfo);254        buttonLocation = await button.getLocation();255      }256      await button.click();257      break;258    }259  }...gutenberg-editor-cover.test.js
Source:gutenberg-editor-cover.test.js  
...51			await editorPage.chooseMediaLibrary();52			// Edit media within block settings53			await settingsButton.click();54			await editorPage.driver.sleep( 2000 ); // Await media load55			const editImageButton = await editorPage.driver.elementsByAccessibilityId(56				'Edit image'57			);58			await editImageButton[ editImageButton.length - 1 ].click();59			// Replace image60			const replaceButton = await editorPage.driver.elementByAccessibilityId(61				'Replace'62			);63			await replaceButton.click();64			// First modal should no longer be presented65			const replaceButtons = await editorPage.driver.elementsByAccessibilityId(66				'Replace'67			);68			// eslint-disable-next-line jest/no-conditional-expect69			expect( replaceButtons.length ).toBe( 0 );70			// Select different media71			await editorPage.chooseMediaLibrary();72		}73		expect( coverBlock ).toBeTruthy();74		await editorPage.removeBlockAtPosition( blockNames.cover );75	} );...listTest.android.js
Source:listTest.android.js  
...41describe('Default List interactions', () => {42    it('should load first 10 elements', async() => {43        // Change to wait for element44        // await driver.sleep(4000);45        const elements = await driver.elementsByAccessibilityId('nameText');46        // **** ANDROID PURPOSES *****47      48        expect(elements.length).to.equal(6);49    });50    it('should load 20 elements after scrolling', async() => {51        const action = new TouchAction(driver);52        const scrollDown = action.press({53                y: 30054            })55            .moveTo({56                y: -100057            }) // drag finger up58            .release(); // release finger59        await driver.performTouchAction(scrollDown);60        // await driver.performTouchAction(scrollDown);61        const elements = await driver.elementsByAccessibilityId('nameText');62        expect(elements.length).to.equal(20);63    });64});65async function tr(param, id) {66    const TEXT = param + '\n\n';67    await driver.elementByAccessibilityId('searchBar')68        .type(TEXT);69    // Change to wait for element70    // await driver.sleep(4000);71    const ele = await driver.elementByAccessibilityId(id).text();72    73    expect(ele).to.have.string(param);74    //Clear75    await driver.elementByAccessibilityId('clearButton').click();...TransactionDetails.e2e.js
Source:TransactionDetails.e2e.js  
...35    .moveTo({ x: 530, y: 1200 })36    .release()37  await action.perform()38  await sleep(1000)39  const hasElement = await driver.elementsByAccessibilityId(transaction.id.toString()).length > 040  expect(hasElement).toBe(false)...by-accessibility-id-e2e-specs.js
Source:by-accessibility-id-e2e-specs.js  
...15  it('should find an element by name', async function () {16    await driver.elementByAccessibilityId('Animation').should.eventually.exist;17  });18  it('should return an array of one element if the `multi` param is true', async function () {19    let els = await driver.elementsByAccessibilityId('Animation');20    els.should.be.an.instanceof(Array);21    els.should.have.length(1);22  });23  it('should find an element with a content-desc property containing an apostrophe', async function () {24    await driver.elementByAccessibilityId("Access'ibility").should.eventually.exist;25  });...AlbumDetail.android.test.js
Source:AlbumDetail.android.test.js  
...7    await driver.resetApp();8    await driver.setImplicitWaitTimeout(20000);9  });10  it('should get Browser window with back button after clicking the "Buy Now" button', async () => {11    const buyButton = await driver.elementsByAccessibilityId('Button').first();12    await buyButton.click();13    const buttonOnce = await driver.elementById('android:id/button_once');14    await buttonOnce.click();15    const target = await driver.elementByAccessibilityId('Taylor Swift');16    expect(target).to.exist;17  });...navigation.js
Source:navigation.js  
...4    await el.click();5  }6}7async function clickBack (driver) {8  let el = (await driver.elementsByAccessibilityId('Back'))[0];9  if (el && (await el.isDisplayed())) {10    await el.click();11  }12}...Using AI Code Generation
1var webdriver = require('selenium-webdriver'),2    until = webdriver.until;3var driver = new webdriver.Builder()4    .forBrowser('selenium')5    .build();6driver.findElement(By.name('q')).sendKeys('webdriver');7driver.findElement(By.name('btnG')).click();8driver.wait(until.titleIs('webdriver - Google Search'), 1000);9driver.quit();10var webdriver = require('selenium-webdriver'),11    until = webdriver.until;12var driver = new webdriver.Builder()13    .forBrowser('selenium')14    .build();15driver.findElement(By.name('q')).sendKeys('webdriver');16driver.findElement(By.name('btnG')).click();17driver.wait(until.titleIs('webdriver - Google Search'), 1000);18driver.quit();19var webdriver = require('selenium-webdriver'),20    until = webdriver.until;21var driver = new webdriver.Builder()22    .forBrowser('selenium')23    .build();24driver.findElement(By.name('q')).sendKeys('webdriver');25driver.findElement(By.name('btnG')).click();26driver.wait(until.titleIs('webdriver - Google Search'), 1000);27driver.quit();28var webdriver = require('selenium-webdriver'),29    until = webdriver.until;30var driver = new webdriver.Builder()31    .forBrowser('selenium')32    .build();33driver.findElement(By.name('q')).sendKeys('webdriver');34driver.findElement(By.name('btnG')).click();35driver.wait(until.titleIsUsing AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3    desiredCapabilities: {4    }5};6var client = webdriverio.remote(options);7    .init()8    .elementsByAccessibilityId('button1')9    .then(function (el) {10        console.log(el);11    })12    .end();Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = { desiredCapabilities: { browserName: 'Safari' } };3var client = webdriverio.remote(options);4  .init()5  .end();6[debug] [MJSONWP] Calling AppiumDriver.findElements() with args: ["-ios uiautomatioUsing AI Code Generation
1var webdriver = require('selenium-webdriver');2var assert = require('assert');3    build();4driver.findElement({name: 'q'}).sendKeys('webdriver');5driver.findElement({name: 'btnG'}).click();6driver.wait(function() {7  return driver.getTitle().then(function(title) {8    return title === 'webdriver - Google Search';9  });10}, 1000);11driver.quit();12var webdriver = require('selenium-webdriver');13var assert = require('assert');14    build();15driver.findElement({name: 'q'}).sendKeys('webdriver');16driver.findElement({name: 'btnG'}).click();17driver.wait(function() {18  return driver.getTitle().then(function(title) {19    return title === 'webdriver - Google Search';20  });21}, 1000);22driver.quit();23var webdriver = require('selenium-webdriver');24var assert = require('assert');25    build();26driver.findElement({name: 'q'}).sendKeys('webdriver');27driver.findElement({name: 'btnG'}).click();28driver.wait(function() {29  return driver.getTitle().then(function(title) {30    return title === 'webdriver - Google Search';31  });32}, 1000);33driver.quit();34var webdriver = require('selenium-webdriver');35var assert = require('assert');36    build();37driver.findElement({name: 'q'}).sendKeys('webdriver');38driver.findElement({name: 'btnG'}).click();39driver.wait(function() {40  return driver.getTitle().then(function(title) {41    return title === 'webdriver - Google Search';Using AI Code Generation
1var wd = require('wd');2var chai = require('chai');3var chaiAsPromised = require('chai-as-promised');4var assert = chai.assert;5chai.use(chaiAsPromised);6var browser = wd.promiseChainRemote("localhost", 4723);7var desired = {8};9browser.setImplicitWaitTimeout(5000);10    .init(desired)11    .elementsByAccessibilityId('mybutton')12    .then(function (els) {13        return els[0].click();14    })15    .fin(function() { return browser.quit(); })16    .done();17var wd = require('wd');18var chai = require('chai');19var chaiAsPromised = require('chai-as-promised');20var assert = chai.assert;21chai.use(chaiAsPromised);22var browser = wd.promiseChainRemote("localhost", 4723);23var desired = {24};Using AI Code Generation
1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5const should = chai.should();6const _ = require('lodash');7const { exec } = require('teen_process');8const { killAllSimulators } = require('node-simctl');9const B = require('bluebird');10const PORT = 4723;11const HOST = 'localhost';12let driver;13let caps = {Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var _ = require('underscore');4var desired = {5};6var driver = wd.promiseChainRemote("localhost", 4723);7  .init(desired)8  .sleep(3000)9  .elementsByAccessibilityId("Search")10  .then(function (els) {11    console.log("elements found: " + els.length);12  })13  .nodeify(done);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!!
