Best JavaScript code snippet using appium
testdrive.js
Source:testdrive.js
1const { Driver, browser, Actions } = require('../index')2;(async () => {3 try {4 /*5 // var actions = new Actions(new Actions.Pointer('mouse'), new Actions.Keyboard('keyboard'))6 var actions = new Actions(new Actions.Keyboard('keyboard'))7 console.log('BEFORE:', actions, '\n\nAND:', actions.actions, '\n\n')8 actions.tick.keyboardUp('r')9 actions.tick.keyboardDown('r').tick.keyboardDown('R')10 actions.tick.keyboardDown('p').compile()11 actions.tick.keyboardUp('p')12 actions.compile()13*/14/*15 var driver = new Driver(new Firefox(), { port: 1000, spawn: false })16 await driver.connect() <--- also runs 'driver.newSession()'17 connect will:18 - Look for a free port. Make 'port' a default settable option19 - Run the browser on that port20 - Make the connection on that port21 - Create a session with driver.newSession()22*/23 //24 // var firefox = new Firefox()25 // var chrome = new Chrome()26 // var driver = new Driver('127.0.0.1', 4444) // 4444 or 951527 // var driver = new Driver(firefox) // 4444 or 951528 // await driver.newSession(firefox)29 // console.log('SESSION: ', await driver.newSession({}))30 // await driver.navigateTo({ url: 'http://www.google.com' })31 // var el = await driver.findElements({ using: Driver.Using.CSS, value: '[name=q]' })32 // console.log('ELEMENTS:', el)33 // console.log('TRY:', await el[0].sendKeys({ text: 'thisworksonfirefox', value: ['c', 'h', 'r', 'o', 'm', 'e'] }))34 // console.log('TRY:', await el[0].sendKeys({ text: 'thisworksonfirefoxandchrome' + Element.KEY.ENTER }))35 var driverChrome = new Driver(new browser.Chrome(), { spawn: true })36 console.log('DriverChrome:', driverChrome)37 var driver = new Driver(new browser.Firefox(), { spawn: true })38 await driver.newSession()39 console.log('Loading Google:', await driver.waitFor(6000, 100).navigateTo('https://www.google.com'))40 await driver.sleep(2000)41 await driver.navigateTo('https://gigsnet.com')42 var el = await driver.findElementCss('body')43 console.log('BODY ELEMENT:', el)44 console.log('GIGSNET', await el.waitFor(10000, 150).findElementsCss('paper-card.my-book-city', (r) => r.length))45 await driver.sleep(3000)46 await driver.navigateTo('http://usejsdoc.org')47 var article = await driver.findElementCss('article')48 console.log('Article:', article)49 console.log('TIMEOUTS:', await driver.getTimeouts())50 // console.log('SETTIMEOUTS:', await driver.setTimeouts({ implicit: 0, pageLoad: 300000, script: 30000 }))51 console.log('TIMEOUTS AGAIN:', await driver.getTimeouts())52 var dts = await article.findElementsCss('dt')53 var dt0Text = await dts[0].getText()54 console.log('TEXT', dt0Text)55 var actions = new Actions(new Actions.Pointer('mouse'), new Actions.Keyboard('keyboard'))56 // var actions = new Actions()57 console.log('BEFORE:', actions, '\n\nAND:', actions.actions, '\n\n')58 actions.tick.mouseDown().keyboardDown('R')59 actions.tick.mouseMove({ origin: dts[3], x: 10, y: 20, duration: 1000 })60 actions.tick.mouseDown().keyboardUp('r')61 actions.tick.mouseUp().tick.keyboardDown('p')62 actions.tick.keyboardUp('p')63 actions.compile()64 await driver.performActions(actions)65 /*66 console.log('Maximize:')67 await driver.maximizeWindow()68 console.log('(done)')69 await driver.sleep(2000)70 console.log('Minimize:')71 await driver.minimizeWindow()72 console.log('(done)')73 await driver.sleep(2000)74 console.log('Maximize again:')75 await driver.maximizeWindow()76 console.log('(done)')77 await driver.sleep(2000)78 console.log('Full screen:')79 await driver.fullScreenWindow()80 console.log('(done)')81 await driver.sleep(2000)82 */83 console.log('Selected:', await dts[0].isSelected())84 console.log('Enabled:', await dts[0].isEnabled())85 var h2 = await driver.findElementCss('h2#block-tags')86 console.log('SEE ATTR:', await h2.getAttribute('id'))87 // console.log('SEE PROP:', await h2.getProperty('id'))88 console.log('SEE CSS VAL:', await h2.getCssValue('height'))89 console.log('SEE TAG NAME VAL:', await h2.getTagName())90 // console.log('SEE RECT:', await h2.getRect())91 console.log('SEE CLICK:', await h2.click())92 // console.log('SEE CLEAR:', await h2.clear())93 // console.log('SEE SCREENSHOT:', await h2.takeScreenshot())94 await driver.waitFor(6000).navigateTo('http://www.google.com')95 console.log('PAGE SOURCE:', await driver.getPageSource())96 // var q = await driver.findElementCss('[name=q]')97 // await q.sendKeys('stocazzo' + Element.KEY.ENTER)98 // console.log('WTF', q, q.id, q.ELEMENT)99 // console.log('EXECUTE 0 PRETEND:')100 // await driver.sleep(5000)101 /*102 console.log('EXECUTE 0:', await driver.executeScript('prompt('pippo');return 'Hello ' + arguments[0];', ['tony']))103 await driver.sleep(2000)104 console.log('Alert text:', await driver.getAlertText())105 await driver.sendAlertText('aaaaa')106 // await driver.dismissAlert()107 await driver.sleep(2000)108 */109 var el2 = await driver.getActiveElement()110 console.log('Active Element:', el2)111 var elsc = await el2.takeScreenshot(true)112 console.log('Active Element screenshot:', elsc)113 var sc = await driver.takeScreenshot()114 console.log('Screenshot:', sc)115 var fs = require('fs')116 fs.writeFileSync('/tmp/elsc.png', elsc)117 fs.writeFileSync('/tmp/sc.png', sc)118 console.log('EXECUTE 1:', await driver.executeAsyncScript("var name = arguments[0];var cb = arguments[1];cb('Hello ' + name);", ['tony']))119 console.log('Cookies', await driver.getAllCookies())120 console.log('Cookie named', await driver.getNamedCookie('NID'))121 console.log('Deleting cookie named', await driver.deleteCookie('NID'))122 console.log('ALL Cookies again', await driver.getAllCookies())123 console.log('Deleting ALL cookies', await driver.deleteAllCookies())124 console.log('ALL Cookies again 2', await driver.getAllCookies())125 console.log('Set cookie', await driver.addCookie({126 name: 'test',127 value: 'a test',128 path: '/',129 domain: 'google.com.au',130 expiry: 1732569047,131 secure: true,132 httpOnly: true133 }))134 console.log('Cookie named test', await driver.getNamedCookie('test'))135 // console.log('EXECUTE 1:', await driver.executeAsyncScript("var a = arguments; var name = a[0]; var cb = a[1]; alert('Hello ' + name); setTimeout( () => { cb('ahah!') }, 2000);", ['tony']))136 // console.log('EXECUTE:', await driver.executeScript("alert('Stocazzo! '+ arguments[0])", ['a', 'b', 'c']))137 console.log('Window handleS:', await driver.getWindowHandles())138 // console.log('Switch to frame:', await driver.switchToFrame(q))139 console.log('Switch to parent frame:', await driver.switchToParentFrame())140 console.log('STATUS:', await driver.status())141 console.log('TITLE:', await driver.getTitle())142 console.log('RECT:', await driver.getWindowRect())143 console.log('SET RECT:', await driver.setWindowRect({x: 10, y: 10, width: 800, height: 800}))144 console.log('CURRNET URL:', await driver.getCurrentUrl())145 console.log('BACK:')146 await driver.back()147 console.log('CURRNET URL:', await driver.getCurrentUrl())148 console.log('BACK:')149 await driver.forward()150 console.log('CURRNET URL:', await driver.getCurrentUrl())151 console.log('Refreshing...')152 await driver.refresh()153 console.log('Window handle:', await driver.getWindowHandle())154 var wn = await driver.getWindowHandle()155 console.log('Switch to window:')156 await driver.switchToWindow(wn)157 console.log('Maximize:')158 await driver.maximizeWindow()159 await driver.sleep(1000)160 console.log('Minimize:')161 await driver.minimizeWindow()162 await driver.sleep(1000)163 console.log('Maximize again:')164 await driver.maximizeWindow()165 await driver.sleep(1000)166 console.log('Full screen:')167 await driver.fullScreenWindow()168 await driver.sleep(1000)169 // await driver.closeWindow()170 await driver.sleep(5000)171 // console.log('TIMEOUTS:', await driver.getTimeouts())172 // console.log('And:', await driver.getCurrentUrl())173 // console.log('EXECUTE:', await driver.closeWindow())174 await driver.deleteSession()175 } catch (e) {176 console.log('ERROR:', e)177 }...
macaca-playwright.test.js
Source:macaca-playwright.test.js
...26 assert(driver);27 });28 it('get should be ok', async () => {29 await driver.get('file://' + path.resolve(__dirname, 'webpages/1.html'));30 await driver.maximize();31 const html = await driver.getSource();32 assert(html.includes('<html>'));33 const uesrAgent = await driver.execute('return navigator.userAgent');34 assert.equal(uesrAgent, customUserAgent);35 });36 it('get title', async () => {37 const title = await driver.title();38 assert.equal(title, 'Document 1');39 });40 it('set window size', async () => {41 await driver.setWindowSize(null, 600, 600);42 });43 it('screenshot', async () => {44 const base64 = await driver.getScreenshot();45 assert(base64.match(/^[0-9a-z\/+=]+$/i));46 });47 it('set input value', async () => {48 const input = await driver.findElement('id', 'input');49 await driver.setValue(input.ELEMENT, 'aaa');50 await driver.clearText(input.ELEMENT);51 await driver.setValue(input.ELEMENT, 'macaca');52 const style = await driver.getComputedCss(input.ELEMENT, 'display');53 assert.equal(style, 'inline-block');54 await _.sleep(500);55 });56 it('element attr', async () => {57 const button = await driver.findElement('id', 'button-1');58 const buttonIsDiaplayed = await driver.isDisplayed(button.ELEMENT);59 assert.equal(buttonIsDiaplayed, true);60 const bgColor = await driver.getComputedCss(button.ELEMENT, 'background-color');61 assert.equal(bgColor, 'rgb(255, 255, 255)');62 });63 it('click button', async () => {64 const button = await driver.findElement('id', 'button-1');65 await driver.click(button.ELEMENT);66 await _.sleep(300);67 const box = await driver.findElement('id', 'target');68 const boxText = await driver.getText(box.ELEMENT);69 assert.equal(boxText, 'macaca');70 });71 it('click link', async () => {72 const link = await driver.findElement('id', 'link-1');73 await driver.click(link.ELEMENT);74 await _.sleep(1000);75 const title = await driver.title();76 assert.equal(title, 'Document 2');77 });78 it('history back', async () => {79 await driver.back();80 await _.sleep(1000);81 await driver.refresh();82 await _.sleep(1000);83 const title = await driver.title();84 assert.equal(title, 'Document 1');85 });86 it('open in new window', async () => {87 const link = await driver.findElement('id', 'link-2');88 await driver.click(link.ELEMENT);89 await driver.maximize();90 await _.sleep(1000);91 });92 it('window handlers', async () => {93 const windows = await driver.getWindows();94 assert.equal(windows.length, 1);95 const title = await driver.title();96 assert.equal(title, 'Document 1');97 });98 after(async () => {99 await driver.stopDevice();100 });101 });...
macaca-puppeteer.test.js
Source:macaca-puppeteer.test.js
...23 assert(driver);24 });25 it('get should be ok', async () => {26 await driver.get('file://' + path.resolve(__dirname, 'webpages/1.html'));27 await driver.maximize();28 const html = await driver.getSource();29 assert(html.includes('<html>'));30 const uesrAgent = await driver.execute('return navigator.userAgent');31 assert.equal(uesrAgent, customUserAgent);32 });33 it('get title', async () => {34 const title = await driver.title();35 assert.equal(title, 'Document 1');36 });37 it('set window size', async () => {38 await driver.setWindowSize(null, 600, 600);39 });40 it('screenshot', async () => {41 const base64 = await driver.getScreenshot();42 assert(base64.match(/^[0-9a-z\/+=]+$/i));43 });44 it('set input value', async () => {45 const input = await driver.findElement('id', 'input');46 await driver.setValue(input.ELEMENT, 'aaa');47 await driver.clearText(input.ELEMENT);48 await driver.setValue(input.ELEMENT, 'macaca');49 const style = await driver.getComputedCss(input.ELEMENT, 'display');50 assert.equal(style, 'inline-block');51 await _.sleep(500);52 });53 it('element attr', async () => {54 const button = await driver.findElement('id', 'button-1');55 const buttonIsDiaplayed = await driver.isDisplayed(button.ELEMENT);56 assert.equal(buttonIsDiaplayed, true);57 const bgColor = await driver.getComputedCss(button.ELEMENT, 'background-color');58 assert.equal(bgColor, 'rgb(255, 255, 255)');59 });60 it('click button', async () => {61 const button = await driver.findElement('id', 'button-1');62 await driver.click(button.ELEMENT);63 await _.sleep(300);64 const box = await driver.findElement('id', 'target');65 const boxText = await driver.getText(box.ELEMENT);66 assert.equal(boxText, 'macaca');67 });68 it('click link', async () => {69 const link = await driver.findElement('id', 'link-1');70 await driver.click(link.ELEMENT);71 await _.sleep(1000);72 const title = await driver.title();73 assert.equal(title, 'Document 2');74 });75 it('history back', async () => {76 await driver.back();77 await _.sleep(1000);78 await driver.refresh();79 await _.sleep(1000);80 const title = await driver.title();81 assert.equal(title, 'Document 1');82 });83 it('open in new window', async () => {84 const link = await driver.findElement('id', 'link-2');85 await driver.click(link.ELEMENT);86 await driver.maximize();87 await _.sleep(1000);88 });89 it('window handlers', async () => {90 const windows = await driver.getWindows();91 assert.equal(windows.length, 1);92 const title = await driver.title();93 assert.equal(title, 'Document 1');94 });95 after(async () => {96 await driver.stopDevice();97 });98 });...
login.test.js
Source:login.test.js
1const loginPage = require("../../pages/sfdc/login.page");2const expect = require("chai").expect;3require("dotenv").config();4describe("Sample Test Suite", () => {5 it("Sample Test Case", async () => {6 await driver.url("/");7 await driver.maximizeWindow();8 await loginPage.setUsername(process.env.SF_USERNAME);9 await loginPage.setPassword(process.env.SF_PASSWORD);10 await loginPage.loginBtnClick();11 await expect(await loginPage.getNameLabel()).to.be.equal("IDFC CA Operations");12 });...
googleSearch2.js
Source:googleSearch2.js
1const googlePageObject = require('../../pageObjects/googlePage')2describe("Second Test Suite",()=>{3 before(async ()=>{4 await driver.url('https://www.google.com')5 await driver.maximizeWindow()6 })7 it("2nd google search in using page object", async ()=>{8 await googlePageObject.searchAndVerifyTitle('flipkart','flipkart - Google Search')9 })...
googleSearch5.js
Source:googleSearch5.js
1const googlePageObject = require('../../pageObjects/googlePage')2describe("Fifth Test Suite",()=>{3 before(async ()=>{4 await driver.url('https://www.google.com')5 await driver.maximizeWindow()6 })7 it("5th google search in using page object", async ()=>{8 await googlePageObject.searchAndVerifyTitle('virat','virat kohli - Google Search')9 })...
googleSearch4.js
Source:googleSearch4.js
1const googlePageObject = require('../../pageObjects/googlePage')2describe("Fourth Test Suite",()=>{3 before(async ()=>{4 await driver.url('https://www.google.com')5 await driver.maximizeWindow()6 })7 it("4th google search in using page object", async ()=>{8 await googlePageObject.searchAndVerifyTitle('elon','elon musk - Google Search')9 })...
googleSearch3.js
Source:googleSearch3.js
1const googlePageObject = require('../../pageObjects/googlePage')2describe("Third Test Suite",()=>{3 before(async ()=>{4 await driver.url('https://www.google.com')5 await driver.maximizeWindow()6 })7 it("3rd google search in using page object", async ()=>{8 await googlePageObject.searchAndVerifyTitle('apple','apple - Google Search')9 })...
Using AI Code Generation
1driver.maximize();2driver.orientation("LANDSCAPE");3driver.isLocked();4driver.lock(5);5driver.unlock();6driver.backgroundApp(5);7driver.hideKeyboard("Done");8driver.isKeyboardShown();9driver.getSettings();10driver.updateSettings();11driver.logTypes();12driver.log("logType");13driver.getDeviceTime();14driver.startActivity("appPackage","appActivity");15driver.installApp("appPath");16driver.removeApp("bundleId");17driver.terminateApp("bundleId");18driver.activateApp("bundleId");19driver.reset();20driver.getPerformanceData("packageName", "dataType", "dataReadTimeout");21driver.getPerformanceDataTypes();22driver.getSupportedPerformanceDataTypes();23driver.startRecordingScreen();24driver.stopRecordingScreen();25driver.getDisplayDensity();26driver.getDisplaySize();27driver.getPageSource();28driver.getSource();
Using AI Code Generation
1driver.maximize();2driver.setOrientation('LANDSCAPE');3driver.getOrientation();4driver.rotate('LANDSCAPE');5driver.getGeoLocation();6driver.setGeoLocation({latitude: 48.8583701, longitude: 2.2922926, altitude: 100});7driver.hideKeyboard();8driver.isKeyboardShown();9driver.getNetworkConnection();10driver.setNetworkConnection(6);11driver.touchId(true);12driver.toggleTouchIdEnrollment(true);13driver.toggleAirplaneMode();14driver.toggleWifi();15driver.toggleData();16driver.toggleLocationServices();17driver.toggleSiri();18driver.toggleVoiceOver();19driver.toggleAutoRotation();20driver.launchApp();21driver.closeApp();22driver.resetApp();23driver.removeApp();24driver.installApp('/path/to/my/app');25driver.activateApp('com.example.myapp');26driver.terminateApp('com.example.myapp');27driver.backgroundApp(5);
Using AI Code Generation
1driver.maximize();2driver.orientation("LANDSCAPE");3driver.orientation("PORTRAIT");4driver.screenshot("screenshot.png");5driver.source();6driver.getPageSource();7driver.getOrientation();8driver.getGeoLocation();9driver.setGeoLocation();10driver.getNetworkConnection();11driver.setNetworkConnection();12driver.getPerformanceData();13driver.getPerformanceDataTypes();14driver.getSettings();15driver.updateSettings();16driver.getDeviceTime();17driver.getDevicePixelRatio();18driver.getDisplayDensity();19driver.getClipboard();20driver.setClipboard();21driver.toggleAirplaneMode();22driver.toggleData();23driver.toggleWiFi();24driver.toggleLocationServices();25driver.toggleWifi();26driver.lock();27driver.unlock();28driver.isLocked();29driver.backgroundApp();30driver.terminateApp();
Using AI Code Generation
1describe('Test to maximize the window', function () {2 it('should maximize the window', function () {3 driver.maximize();4 });5});6describe('Test to minimize the window', function () {7 it('should minimize the window', function () {8 driver.minimize();9 });10});11describe('Test to set the orientation', function () {12 it('should set the orientation', function () {13 driver.setOrientation('LANDSCAPE');14 });15});16describe('Test to get the orientation', function () {17 it('should get the orientation', function () {18 driver.getOrientation();19 });20});21describe('Test to get the page source', function () {22 it('should get the page source', function () {23 driver.getPageSource();24 });25});26describe('Test to get the geo location', function () {27 it('should get the geo location', function () {28 driver.getGeoLocation();29 });30});31describe('Test to set the geo location', function () {32 it('should set the geo location', function () {33 driver.setGeoLocation({latitude: 123.123, longitude: 123.123});34 });35});36describe('Test to get the network connection', function () {37 it('should get the network connection', function () {38 driver.getNetworkConnection();39 });40});41describe('Test to set the network connection', function () {42 it('should set the network connection', function () {43 driver.setNetworkConnection(1);44 });45});46describe('Test to get the performance data', function () {47 it('should get the performance data', function () {
Using AI Code Generation
1driver.maximize()2 .then(function() {3 console.log("Appium driver is maximized");4 })5 .catch(function(err) {6 console.log("Error in maximizing Appium driver", err);7 });8driver.orientation("LANDSCAPE")9 .then(function() {10 console.log("Appium driver is set to landscape");11 })12 .catch(function(err) {13 console.log("Error in setting Appium driver to landscape", err);14 });15driver.context("NATIVE_APP")16 .then(function() {17 console.log("Appium driver is set to native app");18 })19 .catch(function(err) {20 console.log("Error in setting Appium driver to native app", err);21 });22driver.isKeyboardShown()23 .then(function(isShown) {24 console.log("Is keyboard shown: ", isShown);25 })26 .catch(function(err) {27 console.log("Error in checking if keyboard is shown", err);28 });29driver.hideKeyboard()30 .then(function() {31 console.log("Keyboard is hidden");32 })33 .catch(function(err) {34 console.log("Error in hiding keyboard", err);35 });36driver.back()37 .then(function() {38 console.log("Appium driver is set to native app");39 })40 .catch(function(err) {41 console.log("Error in setting Appium driver to native app", err);42 });43driver.touchAction({44})45 .then(function() {46 console.log("Tapped at (100, 100)");47 })48 .catch(function(err) {49 console.log("Error in tapping at (100, 100)", err);50 });51driver.touchAction({
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!!