Best JavaScript code snippet using appium-android-driver
execute-specs.js
Source: execute-specs.js
...12 describe('http', function () {13 const driver = setup(this, desired).driver;14 before(async function () { return await loadWebView(desired, driver); });15 after(async function () {16 await driver.deleteSession();17 });18 describe('synchronous', function () {19 it('should bubble up javascript errors', async function () {20 await driver.execute(`'nan'--`).should.eventually.be.rejected;21 });22 it('should eval javascript', async function () {23 (await driver.execute('return 1')).should.be.equal(1);24 });25 it('should not be returning hardcoded results', async function () {26 (await driver.execute('return 1+1')).should.be.equal(2);27 });28 it(`should return nothing when you don't explicitly return`, async function () {29 expect(await driver.execute('1+1')).to.not.exist;30 });31 it('should execute code inside the web view', async function () {32 (await driver.execute(GET_RIGHT_INNERHTML)).should.be.ok;33 (await driver.execute(GET_WRONG_INNERHTML)).should.not.be.ok;34 });35 it('should convert selenium element arg to webview element', async function () {36 let el = await driver.findElement('id', 'useragent');37 await driver.execute(SCROLL_INTO_VIEW, [el]);38 });39 it('should catch stale or undefined element as arg', async function () {40 let el = await driver.findElement('id', 'useragent');41 await driver.execute(SCROLL_INTO_VIEW, [{'ELEMENT': (el.value + 1)}]).should.be.rejected;42 });43 it('should be able to return multiple elements from javascript', async function () {44 let res = await driver.execute(GET_ELEM_BY_TAGNAME);45 expect(res).to.have.length.above(0);46 });47 it('should pass along non-element arguments', async function () {48 let arg = 'non-element-argument';49 (await driver.execute('var args = Array.prototype.slice.call(arguments, 0); return args[0];', [arg])).should.be.equal(arg);50 });51 it('should handle return values correctly', async function () {52 let arg = ['one', 'two', 'three'];53 (await driver.execute('var args = Array.prototype.slice.call(arguments, 0); return args;', arg)).should.eql(arg);54 });55 });56 describe('asynchronous', function () {57 it('should bubble up javascript errors', async function () {58 await driver.execute(`'nan'--`).should.eventually.be.rejected;59 });60 it('should execute async javascript', async function () {61 await driver.asyncScriptTimeout(1000);62 (await driver.executeAsync(`arguments[arguments.length - 1](123);`)).should.be.equal(123);63 });64 it('should timeout when callback is not invoked', async function () {65 await driver.asyncScriptTimeout(1000);66 await driver.executeAsync(`return 1 + 2`).should.eventually.be.rejected;67 });68 });69 });70 describe('https', function () {71 const driver = setup(this, Object.assign({}, desired, {enableAsyncExecuteFromHttps: true})).driver;72 before(async function () { return await loadWebView(desired, driver, 'https://www.google.com', 'Google'); });73 after(async function () {74 await driver.deleteSession();75 });76 describe('synchronous', function () {77 it('should bubble up javascript errors', async function () {78 await driver.execute(`'nan'--`).should.eventually.be.rejected;79 });80 it('should eval javascript', async function () {81 (await driver.execute('return 1')).should.be.equal(1);82 });83 it('should not be returning hardcoded results', async function () {84 (await driver.execute('return 1+1')).should.be.equal(2);85 });86 it(`should return nothing when you don't explicitly return`, async function () {87 expect(await driver.execute('1+1')).to.not.exist;88 });...
driver-specs.js
Source: driver-specs.js
...91 });92 it('should call setDefaultHiddenApiPolicy', async function () {93 sandbox.stub(driver.adb, 'getApiLevel').returns(28);94 sandbox.stub(driver.adb, 'setDefaultHiddenApiPolicy');95 await driver.deleteSession();96 driver.adb.setDefaultHiddenApiPolicy.calledOnce.should.be.true;97 });98 it('should not call setDefaultHiddenApiPolicy', async function () {99 sandbox.stub(driver.adb, 'getApiLevel').returns(27);100 sandbox.stub(driver.adb, 'setDefaultHiddenApiPolicy');101 await driver.deleteSession();102 driver.adb.setDefaultHiddenApiPolicy.calledOnce.should.be.false;103 });104 });105 describe('#getProxyAvoidList', function () {106 let driver;107 describe('nativeWebScreenshot', function () {108 let proxyAvoidList;109 let nativeWebScreenshotFilter = (item) => item[0] === 'GET' && item[1].test('/session/xxx/screenshot/');110 beforeEach(function () {111 driver = new EspressoDriver({}, false);112 driver.caps = { appPackage: 'io.appium.package', appActivity: '.MainActivity'};113 driver.opts = { autoLaunch: false, skipUnlock: true };114 driver.chromedriver = true;115 sandbox.stub(driver, 'initEspressoServer');...
main.js
Source: main.js
...54 await driver.elementClick(byText('à¸à¸´à¸'));55 } catch (e) {}56 });57 after(function () {58 driver.deleteSession();59 })60 });61}62const loginPass = function(opts) {63 before(async function () {64 this.timeout(50000 * 10000);65 driver = await wdio.remote(opts);66 usernameField = byValueKey('usernameTxt');67 passwordField = byValueKey('passwordTxt');68 loginButton = byValueKey('loginBtn')69 });70 beforeEach(function () {71 if (skip) {72 this.skip();73 }74 });75 afterEach(async function () {76 if (this.currentTest.state == 'failed') {77 var imgName = (this.currentTest.parent.title).replace(/ /g, "_");78 var screenshotPath = 'C:\\Users\\bmais\\Documents\\SeniorHomepro\\E-CatalogTest\\images\\login\\'79 await driver.saveScreenshot(screenshotPath + imgName + '.png');80 skip = true;81 }82 });83 describe('Login to pass', function() {84 it('Log in successful', async function () {85 this.timeout(50000);86 await driver.elementClear(usernameField);87 await driver.elementClear(passwordField);88 await driver.elementSendKeys(usernameField, "551503");89 await driver.elementSendKeys(passwordField, "551505");90 await driver.elementClick(loginButton);91 await driver.execute('flutter:waitForAbsent', loginButton);92 // expect(await driver.getElementText(byText('à¸à¸£à¸°à¸à¸²à¸à¸·à¹à¸')), 'à¸à¸£à¸°à¸à¸²à¸à¸·à¹à¸')93 });94 after(function () {95 driver.deleteSession();96 })97 });98}99module.exports = {100 loginFail,101 loginPass...
general-e2e-specs.js
Source: general-e2e-specs.js
...11 driver = new AndroidDriver();12 await driver.createSession(DEFAULT_CAPS);13 });14 after(async () => {15 await driver.deleteSession();16 });17 it('should launch a new package and activity', async () => {18 let {appPackage, appActivity} = await driver.adb.getFocusedPackageAndActivity();19 appPackage.should.equal('io.appium.android.apis');20 appActivity.should.equal('.ApiDemos');21 let startAppPackage = 'io.appium.android.apis';22 let startAppActivity = '.view.SplitTouchView';23 await driver.startActivity(startAppPackage, startAppActivity);24 let {appPackage: newAppPackage, appActivity: newAppActivity} = await driver.adb.getFocusedPackageAndActivity();25 newAppPackage.should.equal(startAppPackage);26 newAppActivity.should.equal(startAppActivity);27 });28 it('should be able to launch activity with custom intent parameter category', async () => {29 let startAppPackage = 'io.appium.android.apis';30 let startAppActivity = 'io.appium.android.apis.app.HelloWorld';31 let startIntentCategory = 'appium.android.intent.category.SAMPLE_CODE';32 await driver.startActivity(startAppPackage, startAppActivity, undefined, undefined, startIntentCategory);33 let {appActivity} = await driver.adb.getFocusedPackageAndActivity();34 appActivity.should.include('HelloWorld');35 });36 it('should be able to launch activity with dontStopAppOnReset = true', async () => {37 let startAppPackage = 'io.appium.android.apis';38 let startAppActivity = '.os.MorseCode';39 await driver.startActivity(startAppPackage, startAppActivity,40 startAppPackage, startAppActivity,41 undefined, undefined,42 undefined, undefined,43 true);44 let {appPackage, appActivity} = await driver.adb.getFocusedPackageAndActivity();45 appPackage.should.equal(startAppPackage);46 appActivity.should.equal(startAppActivity);47 });48 it('should be able to launch activity with dontStopAppOnReset = false', async () => {49 let startAppPackage = 'io.appium.android.apis';50 let startAppActivity = '.os.MorseCode';51 await driver.startActivity(startAppPackage, startAppActivity,52 startAppPackage, startAppActivity,53 undefined, undefined,54 undefined, undefined,55 false);56 let {appPackage, appActivity} = await driver.adb.getFocusedPackageAndActivity();57 appPackage.should.equal(startAppPackage);58 appActivity.should.equal(startAppActivity);59 });60 });61 describe('getStrings', function () {62 before(async () => {63 driver = new AndroidDriver();64 await driver.createSession(CONTACT_MANAGER_CAPS);65 });66 after(async () => {67 await driver.deleteSession();68 });69 it('should return app strings', async () => {70 let strings = await driver.getStrings('en');71 strings.save.should.equal('Save');72 });73 it('should return app strings for the device language', async () => {74 let strings = await driver.getStrings();75 strings.save.should.equal('Save');76 });77 });...
orientation-e2e-specs.js
Source: orientation-e2e-specs.js
...12 driver = new AndroidDriver();13 });14 afterEach(async function () {15 await driver.setOrientation('PORTRAIT');16 await driver.deleteSession();17 });18 it('should have portrait orientation if requested', async function () {19 await driver.createSession(Object.assign({}, DEFAULT_CAPS, {20 appActivity: '.view.TextFields',21 orientation: 'PORTRAIT',22 }));23 await driver.getOrientation().should.eventually.eql('PORTRAIT');24 });25 it('should have landscape orientation if requested', async function () {26 await driver.createSession(Object.assign({}, DEFAULT_CAPS, {27 appActivity: '.view.TextFields',28 orientation: 'LANDSCAPE',29 }));30 await driver.getOrientation().should.eventually.eql('LANDSCAPE');31 });32 it('should have portrait orientation if nothing requested', async function () {33 await driver.createSession(Object.assign({}, DEFAULT_CAPS, {34 appActivity: '.view.TextFields',35 }));36 await driver.getOrientation().should.eventually.eql('PORTRAIT');37 });38 });39 describe('setting -', function () {40 before(async function () {41 driver = new AndroidDriver();42 await driver.createSession(Object.assign({}, DEFAULT_CAPS, {43 appActivity: '.view.TextFields'44 }));45 });46 after(async () => {47 await driver.deleteSession();48 });49 it('should rotate screen to landscape', async function () {50 await driver.setOrientation('PORTRAIT');51 await B.delay(3000);52 await driver.setOrientation('LANDSCAPE');53 await B.delay(3000);54 await driver.getOrientation().should.eventually.become('LANDSCAPE');55 });56 it('should rotate screen to landscape', async function () {57 await driver.setOrientation('LANDSCAPE');58 await B.delay(3000);59 await driver.setOrientation('PORTRAIT');60 await B.delay(3000);61 await driver.getOrientation().should.eventually.become('PORTRAIT');...
session.js
Source: session.js
...39 remainingAttempts--;40 if (remainingAttempts === 0) {41 throw err;42 } else {43 await this.driver.deleteSession();44 await B.delay(10000);45 await init(remainingAttempts);46 }47 }48 };49 let attempts = this.opts['no-retry'] ? 1 : 3;50 if (env.MAX_RETRY) {51 attempts = Math.min(env.MAX_RETRY, attempts);52 }53 await init(attempts);54 this.initialized = true;55 await this.driver.implicitWait(env.IMPLICIT_WAIT_TIMEOUT);56 }57 async tearDown () {58 if (this.initialized) {59 try {60 await this.driver.deleteSession();61 } catch (err) {62 log.warn("didn't quit cleanly.");63 }64 }65 }66}...
Edition055_Device_Log_Streaming.js
...23 })24 driver.executeScript('mobile:startLogsBroadcast', [])25 await B.delay(5000)26 driver.executeScript('mobile:stopLogsBroadcast', [])27 await driver.deleteSession()28 t.pass()29})30test('stream iOS system logs', async t => {31 driver = await remote({32 hostname: 'localhost',33 port: 4723,34 path: '/wd/hub',35 capabilities: {36 platformName: 'iOS',37 platformVersion: '12.1',38 deviceName: 'iPhone XS',39 automationName: 'XCUITest',40 app: 'https://github.com/cloudgrey-io/the-app/releases/download/v1.6.1/TheApp-v1.6.1.app.zip'41 },42 logLevel: 'error'43 })44 let logStream = websocket(`ws://localhost:4723/ws/session/${driver.sessionId}/appium/device/syslog`)45 logStream.pipe(process.stdout)46 logStream.on('finish', () => {47 console.log('Connection closed, log streaming has stopped')48 })49 driver.executeScript('mobile:startLogsBroadcast', [])50 await B.delay(5000)51 driver.executeScript('mobile:stopLogsBroadcast', [])52 await driver.deleteSession()53 t.pass()...
test.js
Source: test.js
...20 before(async () => {21 driver = await wdio.remote(options)22 })23 after(async () => {24 await driver.deleteSession()25 })26 it('First Test', async () => {27 })28 it('Second Test', async () => {29 })...
Using AI Code Generation
1var webdriver = require('selenium-webdriver'),2 until = webdriver.until;3var driver = new webdriver.Builder()4 .forBrowser('chrome')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();10driver.deleteSession();11driver.quit();
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6var client = webdriverio.remote(options);7 .init()8 .deleteSession()9 .end();10var webdriverio = require('webdriverio');11var options = {12 desiredCapabilities: {13 },
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6var client = webdriverio.remote(options);7 .init()8 .deleteSession()9 .end();10var webdriverio = require('webdriverio');11var options = {12 desiredCapabilities: {13 }14};15var client = webdriverio.remote(options);16 .init()17 .deleteSession()18 .end();19If you are using the Python client, you can use the driver.quit() method. This will close the session and release
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3.forBrowser('chrome')4.build();5driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');6driver.findElement(webdriver.By.name('btnG')).click();7driver.quit();8 .getSession()9 .then(function(session) {10 return driver.deleteSession(session.id);11 })12 .then(function() {13 console.log('Session deleted');14 });15 .getSession()16 .then(function(session) {17 return driver.deleteSession(session.id);18 })19 .then(function() {20 console.log('Session deleted');21 });22 .getSession()23 .then(function(session) {24 return driver.deleteSession(session.id);25 })26 .then(function() {27 console.log('Session deleted');28 });29 .getSession()30 .then(function(session) {31 return driver.deleteSession(session.id);32 })33 .then(function() {34 console.log('Session deleted');35 });36 .getSession()37 .then(function(session) {38 return driver.deleteSession(session.id);39 })40 .then(function() {41 console.log('Session deleted');42 });43 .getSession()44 .then(function(session) {45 return driver.deleteSession(session.id);46 })47 .then(function() {48 console.log('Session deleted');49 });50 .getSession()51 .then(function(session) {52 return driver.deleteSession(session.id);53 })54 .then(function() {55 console.log('Session deleted');56 });57 .getSession()58 .then(function(session) {59 return driver.deleteSession(session.id);60 })61 .then(function() {62 console.log('Session deleted');63 });64 .getSession()
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3 .withCapabilities({4 })5 .build();6driver.quit();
Using AI Code Generation
1driver.deleteSession().then(function() {2 console.log("Session deleted");3 driver.quit();4}, function(err) {5 console.log("Error deleting session");6 console.log(err);7 driver.quit();8});9driver.deleteSession().then(function() {10 console.log("Session deleted");11 driver.quit();12}, function(err) {13 console.log("Error deleting session");14 console.log(err);15 driver.quit();16});17driver.deleteSession().then(function() {18 console.log("Session deleted");19 driver.quit();20}, function(err) {21 console.log("Error deleting session");22 console.log(err);23 driver.quit();24});25driver.deleteSession().then(function() {26 console.log("Session deleted");27 driver.quit();28}, function(err) {29 console.log("Error deleting session");30 console.log(err);31 driver.quit();32});33driver.deleteSession().then(function() {34 console.log("Session deleted");35 driver.quit();36}, function(err) {37 console.log("Error deleting session");38 console.log(err);39 driver.quit();40});41driver.deleteSession().then(function() {42 console.log("Session deleted");43 driver.quit();44}, function(err) {45 console.log("Error deleting session");46 console.log(err);47 driver.quit();48});49driver.deleteSession().then(function() {50 console.log("Session deleted");51 driver.quit();52}, function(err) {53 console.log("Error deleting session");54 console.log(err);55 driver.quit();56});57driver.deleteSession().then(function() {58 console.log("Session deleted");59 driver.quit();60}, function(err) {61 console.log("Error deleting session");62 console.log(err);63 driver.quit();64});65driver.deleteSession().then(function() {66 console.log("Session deleted");67 driver.quit();68}, function(err) {69 console.log("Error deleting session");70 console.log(err);71 driver.quit();72});73driver.deleteSession().then(function() {74 console.log("Session deleted");75 driver.quit();76}, function(err) {77 console.log("Error deleting session");78 console.log(err);79 driver.quit();80});81driver.deleteSession().then(function() {82 console.log("Session deleted");83 driver.quit();84}, function(err) {85 console.log("Error deleting
Using AI Code Generation
1driver.deleteSession();2driver.getCapabilities();3driver.getSession();4driver.getStatus();5driver.getTimeouts();6driver.setTimeouts();7driver.getPageSource();8driver.getSource();9driver.getTitle();10driver.getCurrentActivity();11driver.getCurrentPackage();12driver.getDeviceTime();13driver.getOrientation();
Check out the latest blogs from LambdaTest on this topic:
Testing is a critical step in any web application development process. However, it can be an overwhelming task if you don’t have the right tools and expertise. A large percentage of websites still launch with errors that frustrate users and negatively affect the overall success of the site. When a website faces failure after launch, it costs time and money to fix.
The web development industry is growing, and many Best Automated UI Testing Tools are available to test your web-based project to ensure it is bug-free and easily accessible for every user. These tools help you test your web project and make it fully compatible with user-end requirements and needs.
Desired Capabilities is a class used to declare a set of basic requirements such as combinations of browsers, operating systems, browser versions, etc. to perform automated cross browser testing of a web application.
Manual cross browser testing is neither efficient nor scalable as it will take ages to test on all permutations & combinations of browsers, operating systems, and their versions. Like every developer, I have also gone through that ‘I can do it all phase’. But if you are stuck validating your code changes over hundreds of browsers and OS combinations then your release window is going to look even shorter than it already is. This is why automated browser testing can be pivotal for modern-day release cycles as it speeds up the entire process of cross browser compatibility.
Mobile devices and mobile applications – both are booming in the world today. The idea of having the power of a computer in your pocket is revolutionary. As per Statista, mobile accounts for more than half of the web traffic worldwide. Mobile devices (excluding tablets) contributed to 54.4 percent of global website traffic in the fourth quarter of 2021, increasing consistently over the past couple of years.
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!!