Best JavaScript code snippet using appium
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 wd = require('wd'),2    serverConfigs = require('./appium-servers');3var driver = wd.promiseChainRemote(serverConfigs.local);4driver.init({5}).then(function () {6    return driver.elementsByAccessibilityId('Animation');7}).then(function (els) {8    return els[0].click();9}).then(function () {10    return driver.elementsByAccessibilityId('Bouncing Balls');11}).then(function (els) {12    return els[0].click();13}).then(function () {14    return driver.quit();15}).done();16var serverConfigs = {17    local: {18    }19};20module.exports = serverConfigs;Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desiredCaps = {4};5var driver = wd.promiseChainRemote('localhost', 4723);6    .init(desiredCaps)7    .then(function() {8        driver.elementsByAccessibilityId('digit_5').click();9        driver.elementsByAccessibilityId('op_add').click();10        driver.elementsByAccessibilityId('digit_9').click();11        driver.elementsByAccessibilityId('eq').click();12        driver.elementsByAccessibilityId('result').text().then(function(text) {13            assert.equal(text, "14");14        });15    })16    .fin(function() {17        return driver.quit();18    })19    .done();20{21  "scripts": {22  },23  "dependencies": {24  }25}Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desiredCaps = {4};5var driver = wd.promiseChainRemote('localhost', 4723);6driver.init(desiredCaps).then(function() {7  return driver.elementsByAccessibilityId('digit_1').click();8}).then(function() {9  return driver.elementsByAccessibilityId('op_add').click();10}).then(function() {11  return driver.elementsByAccessibilityId('digit_9').click();12}).then(function() {13  return driver.elementsByAccessibilityId('eq').click();14}).then(function() {15  return driver.elementsByAccessibilityId('result').text();16}).then(function(text) {17  assert.equal(text, '10');18}).fin(function() {19  return driver.quit();20}).done();21var wd = require('wd');22var assert = require('assert');23var desiredCaps = {24};25var driver = wd.promiseChainRemote('localhost', 4723);26driver.init(desiredCaps).then(function() {27}).then(function() {28}).then(function() {29}).then(function() {30}).then(function() {31}).then(function(text) {32  assert.equal(text, '10');33}).fin(function() {34  return driver.quit();35}).done();36var wd = require('Using AI Code Generation
1var wd = require("wd");2var assert = require('assert');3var desired = {4};5driver.init(desired).then(function() {6  return driver.elementsByAccessibilityId("digit_1");7}).then(function(elements) {8  console.log("The number of elements found is: " + elements.length);9  return elements[0].click();10}).then(function() {11  return driver.elementsByAccessibilityId("digit_2");12}).then(function(elements) {13  console.log("The number of elements found is: " + elements.length);14  return elements[0].click();15}).then(function() {16  return driver.elementsByAccessibilityId("op_add");17}).then(function(elements) {18  console.log("The number of elements found is: " + elements.length);19  return elements[0].click();20}).then(function() {21  return driver.elementsByAccessibilityId("digit_3");22}).then(function(elements) {23  console.log("The number of elements found is: " + elements.length);24  return elements[0].click();25}).then(function() {26  return driver.elementsByAccessibilityId("eq");27}).then(function(elements) {28  console.log("The number of elements found is: " + elements.length);29  return elements[0].click();30}).then(function() {31  return driver.elementsByAccessibilityId("result");32}).then(function(elements) {33  console.log("The number of elements found is: " + elements.length);Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desired = {4};5driver.init(desired).then(function() {6  driver.elementsByAccessibilityId('TestApp').then(function(elements) {7    assert.equal(elements.length, 1);8  });9});10driver.quit();11info: Welcome to Appium v1.4.13 (REV 3e3d3e3d3b3e3d3e3b3e3d3e3b3e3d3e3b3e3d3e)Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desiredCaps = {4};5var driver = wd.promiseChainRemote('localhost', 4723);6  .init(desiredCaps)7  .elementsByAccessibilityId('clear')8  .then(function(el) {9    console.log(el);10  })11  .quit();12var wd = require('wd');13var assert = require('assert');14var desiredCaps = {15};16var driver = wd.promiseChainRemote('localhost', 4723);17  .init(desiredCaps)18  .elementByAccessibilityId('clear')19  .then(function(el) {20    console.log(el);21  })22  .quit();23var wd = require('wd');24var assert = require('assert');25var desiredCaps = {26};27var driver = wd.promiseChainRemote('localhost', 4723);28  .init(desiredCaps)29  .elementByAccessibilityId('clear')30  .click()31  .quit();Using AI Code Generation
1driver.elementsByAccessibilityId("username", function(err, elements) {2});3driver.elementsByAccessibilityId("username", function(err, elements) {4});5driver.elementsByAccessibilityId("username", function(err, elements) {6});7driver.elementsByAccessibilityId("username", function(err, elements) {8});9driver.elementsByAccessibilityId("username", function(err, elements) {10});11driver.elementsByAccessibilityId("username", function(err, elements) {12});13driver.elementsByAccessibilityId("username", function(err, elements) {14});15driver.elementsByAccessibilityId("username", function(err, elements) {16});17driver.elementsByAccessibilityId("username", function(err, elements) {18});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!!
