Best JavaScript code snippet using appium
element-e2e-specs.js
Source:element-e2e-specs.js  
...114        await driver.back();115      });116      describe('set value', () => {117        it('should type in the text field', async () => {118          let el = await driver.elementByClassName('XCUIElementTypeTextField');119          await el.type(text1);120          let text = await el.text();121          text.should.eql(text1);122        });123        it('should type in the text field even before the keyboard is up', async () => {124          let el = await driver.elementByClassName('XCUIElementTypeTextField');125          await el.type(text1);126          let text = await el.text();127          text.should.eql(text1);128        });129        it('should type a url in the text field', async () => {130          // in Travis this sometimes gets the wrong text131          let retries = process.env.TRAVIS ? 5 : 1;132          await retryInterval(retries, 100, async () => {133            let el = await driver.elementByClassName('XCUIElementTypeTextField');134            await el.clear();135            await el.type(text3);136            let text = await el.text();137            text.should.eql(text3);138          });139        });140        it('should be able to type into two text fields', async () => {141          let els = await driver.elementsByClassName('XCUIElementTypeTextField');142          await els[0].type(text1);143          await driver.hideKeyboard();144          await els[1].type(text2);145          let text = await els[0].text();146          text.should.eql(text1);147          text = await els[1].text();148          text.should.eql(text2);149        });150        it('should type in a secure text field', async () => {151          let els = await driver.elementsByClassName('XCUIElementTypeSecureTextField');152          await els[0].type(text1);153          let text = await els[0].text();154          text.should.not.eql(text1);155          text.length.should.eql(text1.length);156          text.should.eql(secureText);157        });158        it('should type a backspace', async () => {159          let el = await driver.elementByClassName('XCUIElementTypeTextField');160          await driver.type(el, ['0123456789\uE003']);161          let text = await el.text();162          text.should.eql('012345678');163        });164        it('should type a delete', async () => {165          let el = await driver.elementByClassName('XCUIElementTypeTextField');166          await driver.type(el, ['0123456789\ue017']);167          let text = await el.text();168          text.should.eql('012345678');169        });170        it('should type a newline', async () => {171          let el = await driver.elementByClassName('XCUIElementTypeTextField');172          await driver.type(el, ['0123456789\uE006']);173          let text = await el.text();174          text.should.eql('0123456789');175        });176      });177      describe('clear', () => {178        it('should clear a text field', async () => {179          let el = await driver.elementByClassName('XCUIElementTypeTextField');180          await el.type(text1);181          let text = await el.text();182          text.should.eql(text1);183          await el.clear();184          text = await el.text();185          text.should.eql(phText);186        });187        it('should be able to clear two text fields', async () => {188          let els = await driver.elementsByClassName('XCUIElementTypeTextField');189          await els[0].type(text1);190          let text = await els[0].text();191          text.should.eql(text1);192          await driver.hideKeyboard();193          await els[1].type(text2);194          text = await els[1].text();195          text.should.eql(text2);196          await els[0].clear();197          text = await els[0].text();198          text.should.eql(phText);199          await driver.hideKeyboard();200          await els[1].clear();201          text = await els[1].text();202          text.should.eql(phText);203        });204        it('should clear a secure text field', async () => {205          let el = await driver.elementByClassName('XCUIElementTypeSecureTextField');206          await el.type(text1);207          let text = await el.text();208          text.should.eql(secureText);209          await el.clear();210          text = await el.text();211          text.should.eql(phText);212        });213      });214      describe('keys', () => {215        it('should be able to send text to the active element', async () => {216          let el = await driver.elementByClassName('XCUIElementTypeTextField');217          // make sure the keyboard is up218          await el.click();219          await driver.keys('this is a test');220        });221        it('should type a backspace', async () => {222          let el = await driver.elementByClassName('XCUIElementTypeTextField');223          // make sure the keyboard is up224          await el.click();225          await driver.keys('0123456789\uE003');226          let text = await el.text();227          text.should.eql('012345678');228        });229        it('should type a delete', async () => {230          let el = await driver.elementByClassName('XCUIElementTypeTextField');231          // make sure the keyboard is up232          await el.click();233          await driver.keys('0123456789\ue017');234          let text = await el.text();235          text.should.eql('012345678');236        });237        it('should type a newline', async () => {238          let el = await driver.elementByClassName('XCUIElementTypeTextField');239          // make sure the keyboard is up240          await el.click();241          await driver.keys('0123456789\uE006');242          let text = await el.text();243          text.should.eql('0123456789');244        });245      });246      describe('hide keyboard', () => {247        it('should be able to hide the keyboard', async () => {248          let el = await driver.elementByClassName('XCUIElementTypeTextField');249          await el.click();250          let db = await driver.elementByAccessibilityId('Done');251          (await db.isDisplayed()).should.be.true;252          await driver.hideKeyboard();253          // pause for a second to allow keyboard to go out of view254          // otherwise slow systems will reject the search for `Done` and255          // fast ones will get the element but it will be invisible256          await B.delay(1000);257          db = await driver.elementByAccessibilityId('Done').should.eventually.be.rejected;258        });259      });260    });261    describe('picker wheel', () => {262      it('should be able to set the value', async () => {...ios-complex.js
Source:ios-complex.js  
...190    });191  }192  it("should retrieve an element size", function () {193    return Q.all([194      driver.elementByClassName('XCUIElementTypeTable').getSize(),195      driver.elementByClassName('XCUIElementTypeCell').getSize(),196    ]).then(function (sizes) {197      sizes[0].width.should.equal(sizes[1].width);198      sizes[0].height.should.not.equal(sizes[1].height);199    });200  });201  it("should get the source", function () {202    var mainMenuSource;203    // main menu source204    return driver205      .source().then(function (source) {206        mainMenuSource = source;207        mainMenuSource.should.include('XCUIElementTypeStaticText');208        mainMenuSource.should.include('Text Fields');209      })...calc-app-1-specs.js
Source:calc-app-1-specs.js  
...17          return function () { return elem.clear(); };18        });19        return sequence.reduce(Q.when, new Q()); // running sequence20      }).then(function () {21        return driver.elementByClassName('UIAButton').click();22      });23  };24  var populate = function (type, driver) {25    values = [];26    return driver27      .elementsByIosUIAutomation(filterVisible('.textFields();'))28      .then(function (elems) {29        var sequence = _(elems).map(function (elem) {30          var val = Math.round(Math.random() * 10);31          values.push(val);32          if (type === "elem") {33            return function () { return elem.sendKeys(val); };34          } else if (type === "elem-setvalue") {35            return function () { return elem.setImmediateValue(val); };...PersonalCenterCase.js
Source:PersonalCenterCase.js  
1var app = require('../app');2var driver = app.driver;3var _p = require('../utils/helpers/promise-utils')4import StartScreen from '../screens/StartScreen';5import PersonalCenterScreen from '../screens/PersonalCenterScreen';6import XCUIElementType from '../utils/UIElementType';7describe("login", function () {8    this.timeout(300000);9    var startScreen = new StartScreen(driver);10    var personalCenterScreen = new PersonalCenterScreen(driver);11    var titles = ["", "", "æç伿 å¸", "æçè±ç²", "æçé¶è¡å¡", "æçæ¶è", "æµè§è®°å½", "æ¨èæå¥", "æè§åé¦", "è系客æ", "å
³äºä¹è"];12    // 0 表示è¦ä¸æ£æ¥ï¼1表示éè¦ç»å½ï¼2表示ä¸éè¦ç»å½13    var checkFlag = [0, 0, 1, 1, 1, 1, 2, 2, 1, 1, 2];14    // global setUp, tearDown15    before(function () {16        return app.connect()17            .then(() => {18                return startScreen.closeStartButton();19            })20            .elementByName('æçèå·¢')21            .click()22            .sleep(1000);23    });24    after(function () {25        return driver.quit();26    });27    it('should have 11 cells; æçèå·¢è¦æ11个cell', function () {28        return driver29            .elementByClassName(XCUIElementType.Table)30            .elementsByClassName('>', XCUIElementType.Cell)31            .then((els) => {32                els.should.have.lengthOf(11);33                return els;34            });35    });36    it('should print cell name in order', function () {37        return driver38            .elementByClassName(XCUIElementType.Table)39            .elementsByClassName('>', XCUIElementType.Cell)40            .then(_p.each((el, i) => {41                if (titles[i] == "") {42                    return driver;43                }44                // è¿éä¸éè¦å  '>'ï¼å ä¸ºè°ç¨æ¹æ¯elementï¼å
¶ä¸ä¸æå·²ç»å¯ä»¥ç¡®å®æ¯å½åå
ç´ äº45                return el.elementsByClassName(XCUIElementType.StaticText)46                    // various checks47                    .first().getAttribute('value')48                    .should.become(titles[i]);49            }));50    })51    it('should show login view', () => {52        return driver53            .elementByClassName(XCUIElementType.Table)54            .elementsByClassName('>', XCUIElementType.Cell)55            .then(_p.each((el, i) => {56                if (checkFlag[i] == 0) {57                    return driver;58                }59                console.log('current cell: ' + titles[i] + "   " + i);60                var buttonName = (checkFlag[i] == 1 ? 'login close' : 'back');61                if (i == 10) {62                    buttonName = "order button back";63                }64                return el65                    .isDisplayed()66                    .then((displayed) => {67                        if (displayed == false) {68                            return driver69                                .elementByClassName(XCUIElementType.Table)70                                .then(() => {71                                    return driver.swipe({72                                        startX: 100, startY: 400,73                                        offsetX: 0, offsetY: -600, duration: 40074                                    })75                                })76                                .then(() => {77                                    return el;78                                });79                        }80                        else {81                            return el;82                        }83                    })84                    .click()85                    .sleep(1000)86                    .elementByName(buttonName)87                    .should.eventually.exist88                    .click()89                    .sleep(1000);90            }));91    })...mainPage.js
Source:mainPage.js  
1/*************************************************************************2 *3 * REV SOFTWARE CONFIDENTIAL4 *5 * [2013] - [2017] Rev Software, Inc.6 * All Rights Reserved.7 *8 * NOTICE:  All information contained herein is, and remains9 * the property of Rev Software, Inc. and its suppliers,10 * if any.  The intellectual and technical concepts contained11 * herein are proprietary to Rev Software, Inc.12 * and its suppliers and may be covered by U.S. and Foreign Patents,13 * patents in process, and are protected by trade secret or copyright law.14 * Dissemination of this information or reproduction of this material15 * is strictly forbidden unless prior written permission is obtained16 * from Rev Software, Inc.17 */18"use strict";19var wd = require('wd');20var App = {21    menuBtn: {22        button: 'android.widget.ImageView'23    },24    menuOptions: {25        main: '//android.widget.TextView[@text=\'Main\']',26        configurationView: '//android.widget.TextView[@text=\'Configuration view\']',27        statsView: '//android.widget.TextView[@text=\'Statistic view\']',28        openDrawer: '//android.widget.TextView[@text=\'Open drawer\']'29    },30    input: {31        url: 'com.nuubit.tester:id/tlQuery'32    },33    button: {34        send: 'com.nuubit.tester:id/rlRun',35        fetchConfig: 'com.nuubit.tester:id/bUpdateConfig',36        sendStats: 'com.nuubit.tester:id/bSendReports'37    },38    layoutCountersPage: 'com.nuubit.tester:id/action_bar_root',39    getInputUrl: function (driver) {40        return driver41            .elementById(App.input.url);42    },43    clickSendBtn: function (driver) {44        return driver45            .elementById(App.button.send)46            .click();47    },48    clickSendStatsBtn: function (driver) {49        return driver50            .elementById(App.button.sendStats)51            .click();52    },53    clickFetchConfigBtn: function (driver) {54        return driver55            .elementById(App.button.fetchConfig)56            .click();57    },58    getMainPage: function (driver) {59        return driver60            .elementByClassName(App.menuBtn.button)61            .click()62            .sleep(2000)63            .elementByXPath(App.menuOptions.main)64            .click()65            .sleep(2000);66    },67    getConfigurationPage: function (driver) {68        return driver69            .elementByClassName(App.menuBtn.button)70            .click()71            .sleep(2000)72            .elementByXPath(App.menuOptions.configurationView)73            .click()74            .sleep(2000);75    },76    getStatsPage: function (driver) {77        return driver78            .elementByClassName(App.menuBtn.button)79            .click()80            .sleep(2000)81            .elementByXPath(App.menuOptions.statsView)82            .click()83            .sleep(2000);84    },85    getCountersPage: function (driver) {86        return driver87            .elementByClassName(App.menuBtn.button)88            .click()89            .sleep(2000)90            .elementByXPath(App.menuOptions.openDrawer)91            .click()92            .sleep(2000);93    },94    closeCountersPage: function (driver) {95        var TouchAction = wd.TouchAction;96        var action = new TouchAction(driver);97        return driver98            .elementById(App.layoutCountersPage)99            .then(function(){100                action101                    .press({x: 50, y: 200})102                    .release();103                return action.perform();104            })105    },106    clickMenuButton: function (driver) {107        return driver108            .elementByClassName(App.menuBtn.button)109            .click()110            .sleep(2000);111    },112    clickConfigViewButton: function (driver) {113        return driver114            .elementByXPath(App.menuOptions.configurationView)115            .click()116            .sleep(2000);117    },118     clickStatsViewButton: function (driver) {119         return driver120             .elementByXPath(App.menuOptions.statsView)121             .click()122             .sleep(2000);123     }124};...clear-specs.js
Source:clear-specs.js  
1"use strict";2var setup = require("../../common/setup-base")3 ,  desired = require('./desired');4describe('testapp - clear', function () {5  var driver;6  setup(this, desired).then(function (d) { driver = d; });7  it('should clear the text field', function (done) {8    driver9      .elementByClassName('UIATextField').sendKeys("some-value").text()10        .should.become("some-value")11      .elementByClassName('UIATextField').clear().text().should.become('')12      .nodeify(done);13  });14  // Tap outside hide keyboard strategy can only be tested in UICatalog15  // these tests need to be moved out of "clear-specs", and consolidated with the16  // UICatalog ones17  it('should hide keyboard using "Done" key', function (done) {18    driver19      .elementByClassName('UIATextField').sendKeys("1")20      .elementByClassName('UIASwitch').isDisplayed()21        .should.become(false)22      .hideKeyboard("Done")23      .elementByClassName('UIASwitch').isDisplayed()24        .should.become(true)25      .nodeify(done);26  });27  it('should hide keyboard using "pressKey" strategy with "Done" key', function (done) {28    driver29      .elementByClassName('UIATextField').sendKeys("1")30      .elementByClassName('UIASwitch').isDisplayed()31        .should.become(false)32      .hideKeyboard({strategy: 'pressKey', key: "Done"} )33      .elementByClassName('UIASwitch').isDisplayed()34        .should.become(true)35      .nodeify(done);36  });37  it('should hide keyboard using "pressKey" strategy with "Done" keyName', function (done) {38    driver39      .elementByClassName('UIATextField').sendKeys("1")40      .elementByClassName('UIASwitch').isDisplayed()41        .should.become(false)42      .hideKeyboard({strategy: 'pressKey', keyName: "Done"} )43      .elementByClassName('UIASwitch').isDisplayed()44        .should.become(true)45      .nodeify(done);46  });47  it('should hide keyboard using "press" strategy with "Done" key', function (done) {48    driver49      .elementByClassName('UIATextField').sendKeys("1")50      .elementByClassName('UIASwitch').isDisplayed()51        .should.become(false)52      .hideKeyboard({strategy: 'press', key: "Done"} )53      .elementByClassName('UIASwitch').isDisplayed()54        .should.become(true)55      .nodeify(done);56  });57  // swipedown just doesn't work with testapp58  it.skip('should hide keyboard using "swipeDown" strategy', function (done) {59    driver60      .elementByClassName('UIATextField').sendKeys("1")61      .elementByClassName('UIASwitch').isDisplayed()62        .should.become(false)63      .hideKeyboard({strategy: 'swipeDown'} )64      .elementByClassName('UIASwitch').isDisplayed()65        .should.become(true)66      .nodeify(done);67  });...typing-stress-e2e-specs.js
Source:typing-stress-e2e-specs.js  
...24      await driver.execute('mobile: scroll', {element: tfEl, toVisible: true});25      await tfEl.click();26      // wait for there to be text fields present27      await retryInterval(5, 500, async function () {28        await driver.elementByClassName('XCUIElementTypeTextField').clear();29      });30    });31    afterEach(async function () {32      await driver.elementByClassName('XCUIElementTypeTextField').clear();33    });34    for (let i = 0; i < TYPING_TRIES; i++) {35      it(`should not fail in typing (try #${i + 1})`, async function () {36        const el = await driver.elementByClassName('XCUIElementTypeTextField');37        await el.type(text);38        (await el.text()).should.include(text);39      });40    }41  });...from-el-specs.js
Source:from-el-specs.js  
...6describe("apidemo - find - from element", function () {7  var driver;8  setup(this, desired).then(function (d) { driver = d; });9  it('should find a single element by tag name', function (done) {10    driver.elementByClassName(alv).then(function (el) {11      return el12        .elementByClassName(atv).text().should.become("Access'ibility");13    }).nodeify(done);14  });15  it('should find multiple elements by tag name', function (done) {16    driver.elementByClassName(alv).then(function (el) {17      return el18        .elementsByClassName(atv).should.eventually.have.length.at.least(10);19    }).nodeify(done);20  });21  it('should not find an element that doesnt exist', function (done) {22    driver.elementByClassName(alv).then(function (el) {23      return el24        .elementByClassName("blargimarg").should.be.rejectedWith(/status: 7/);25    }).nodeify(done);26  });27  it('should not find multiple elements that dont exist', function (done) {28    driver.elementByClassName(alv).then(function (el) {29      return el30        .elementsByClassName("blargimarg").should.eventually.have.length(0);31    }).nodeify(done);32  });...Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desired = {4};5var browser = wd.remote("localhost", 4723);6browser.init(desired, function() {7    browser.elementByClassName('android.widget.TextView', function(err, el) {8        el.text(function(err, text) {9            console.log(text);10        });11    });12});13Error: MJSONWP response status is 6, should be 0 (original error: 6)14    at Object.wrappedLogger.errorAndThrow (C:\Users\XXXXXX\AppData\Roaming15    at wrappedCallback (C:\Users\XXXXXX\AppData\Roaming16    at wrappedCallback (C:\Users\XXXXXX\AppData\Roaming17    at wrappedCallback (C:\Users\XXXXXX\AppData\RoamingUsing AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3    desiredCapabilities: {4    }5};6    .remote(options)7    .init()8    .elementByClassName('UIAButton')9    .click()10var webdriverio = require('webdriverio');11var options = {12    desiredCapabilities: {13    }14};15    .remote(options)16    .init()17    .elementByAccessibilityId('Search')18    .click()Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var driver = wd.remote("localhost",4723);4driver.init({browserName:'iOS',platformName:'iOS',platformVersion:'8.3',deviceName:'iPhone Simulator',app:'/Users/username/Desktop/appium/Calculator.app'}, function() {5driver.elementByClassName('UIAButton', function(err, el) {6assert.ok(!err);7console.log("Element Found");8});9});10var wd = require('wd');11var assert = require('assert');12var driver = wd.remote("localhost",4723);13driver.init({browserName:'iOS',platformName:'iOS',platformVersion:'8.3',deviceName:'iPhone Simulator',app:'/Users/username/Desktop/appium/Calculator.app'}, function() {14driver.findElements('class name','UIAButton', function(err, el) {15assert.ok(!err);16console.log("Elements Found");17});18});Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desired = {4};5var browser = wd.remote('localhost', 4723);6browser.init(desired, function() {7    browser.elementByClassName('gbqfif', function(err, el) {8      assert.ok(!err);9      browser.quit();10    });11  });12});13info: Welcome to Appium v1.1.0 (REV 5f8a2e2c2f2e1f1c8d8b7c0f1e1b9c9d0fb8f4c4)Using AI Code Generation
1var wd = require('wd');2var driver = wd.remote("localhost", 4723);3driver.init({platformName:'Android', deviceName:'emulator-5554', app: 'C:/Users/.../app-debug.apk'}, function() {4driver.elementByClassName("android.widget.Button", function(err, el) {5el.click(function(err) {6console.log("clicked on the element");7});8});9});10var wd = require('wd');11var driver = wd.remote("localhost", 4723);12driver.init({platformName:'Android', deviceName:'emulator-5554', app: 'C:/Users/.../app-debug.apk'}, function() {13driver.elementByClassName("android.widget.Button", function(err, el) {14el.click(function(err) {15console.log("clicked on the element");16});17});18});19var wd = require('wd');20var driver = wd.remote("localhost", 4723);21driver.init({platformName:'Android', deviceName:'emulator-5554', app: 'C:/Users/.../app-debug.apk'}, function() {22driver.elementByClassName("android.widget.Button", function(err, el) {23el.click(function(err) {24console.log("clicked on the element");25});26});27});28driver.elementByClassName("android.widget.Button", function(err, el) {29  el.click(function(err) {30    console.log("clicked on the element");31  });32});33driver.elementByClassName("android.widget.Button", function(err, el) {34  el.click(function(err) {35    console.log("clicked on the element");36  });37});Using AI Code Generation
1driver.elementByClassName("UIAButton", function(err, el) {2    if (err) return console.log(err);3    el.click(function(err) {4        if (err) return console.log(err);5    });6});7driver.elementByClassName("UIAButton", function(err, el) {8    if (err) return console.log(err);9    el.click(function(err) {10        if (err) return console.log(err);11    });12});13driver.elementByClassName("UIAButton", function(err, el) {14    if (err) return console.log(err);15    el.click(function(err) {16        if (err) return console.log(err);17    });18});19driver.elementByClassName("UIAButton", function(err, el) {20    if (err) return console.log(err);21    el.click(function(err) {22        if (err) return console.log(err);23    });24});25driver.elementByClassName("UIAButton", function(err, el) {26    if (err) return console.log(err);27    el.click(function(err) {28        if (err) return console.log(err);29    });30});31driver.elementByClassName("UIAButton", function(err, el) {32    if (err) return console.log(err);33    el.click(function(err) {34        if (err) return console.log(err);35    });36});37driver.elementByClassName("UIAButton", functionLearn 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!!
