Best JavaScript code snippet using appium
commonConditions.js
Source:commonConditions.js
...46 }47 if (profile.accountClosed) {48 await patchAccountStatus(personId, false)49 }50 const appBundleId = await driver.getCurrentPackage() // Esto saca el valor de appbundleId51 const { deviceId, magicLinkBaseUrl } = World52 const actionToken = await browser.call(async() => await linkAccountToken(email, deviceId, appBundleId))53 await browser.url(`${magicLinkBaseUrl}/link-account?token=${actionToken}`)54})55Given('get login token with user email {string}', { timeout: 130000 }, async email => {56 const persons = await getPersonByEmail(email)57 const person = await find(persons, { type: 'CUSTOMER' })58 const { id: personId, maritalStatus, profile } = person59 World.personId = personId60 World.email = email61 await unlockAllRestrictions(personId)62 await setKeycloakUserState(personId, true)63 await logOutAllSessions(personId) //uncomment this block and run with VPN to unlock user from keylock64 //browser.call(() => unlinkAllDevices(personId))65 if (driver.isAndroid === true) {66 const appBundleId = await driver.getCurrentPackage() // Esto saca el valor de appbundleId67 const { deviceId, magicLinkBaseUrl } = World68 const actionToken = await linkAccountToken(email, deviceId, appBundleId)69 World.actionToken = actionToken70 await browser.url(`${magicLinkBaseUrl}/link-account?token=${actionToken}`)71 } else {72 const appBundleId = 'ar.com.bdsol.bds.squads.multicolor' // Esto saca el valor de appbundleId73 const { deviceId, magicLinkBaseUrl } = World74 const actionToken = await linkAccountToken(email, deviceId, appBundleId)75 World.actionToken = actionToken76 //driver.execute('mobile: launchApp', {bundleId: 'com.apple.mobilesafari'});77 await driver.execute('mobile: launchApp', { bundleId: 'com.google.chrome.ios' })78 const newTab = await $('~New Tab')79 const nuevoTab = await $('~Crear nueva pestaña.')80 const backButton = await $('//*[@name="Volver" or @name="Back"]')81 const urlButton2 = await $('//*[@name="Busca o escribe una URL" or @name="Search or type URL"]')82 for (let i = 0; i < 2; i++) {83 try {84 if (await newTab.isDisplayed()) {85 await newTab.click()86 break;87 } else if (await nuevoTab.isDisplayed()){88 await nuevoTab.click()89 break;90 } else if (await backButton.isEnabled()){91 await backButton.click()92 } else if (await urlButton2.isDisplayed()){93 break;94 } else {95 await browser.pause(2000) 96 }97 } catch(error){98 console.log('No se pudo ejecutar el magiclink en chrome')99 }100 } 101 const urlButton = await $('//*[@name="Busca o escribe una URL" or @name="Search or type URL"]')102 const address = await $('~Address')103 104 for (let i = 0; i < 2; i++) {105 try {106 if (await urlButton.isDisplayed() || await urlButton.isEnabled()) {107 await urlButton.click() 108 await urlButton.setValue(`${magicLinkBaseUrl}/link-account?token=${actionToken}\uE007`) 109 break;110 } else if (await address.isDisplayed()){111 await address.click() 112 await address.setValue(`${magicLinkBaseUrl}/link-account?token=${actionToken}\uE007`) 113 break;114 }115 } catch(error){116 throw new Error(117 ' No se pudo ejecutar el magiclink en chrome'118 );119 }120 } 121 const openBds = await $('~Abrir Banco del Sol')122 await openBds.click()123 const openSelector =124 "type == 'XCUIElementTypeButton' && name CONTAINS 'Abrir' || type == 'XCUIElementTypeButton' && name CONTAINS 'Open'"125 const openButton = await $(`-ios predicate string:${openSelector}`)126 if (await openButton.isDisplayed()) {127 await openButton.click()128 }129 }130})131Given('user {string} already has {int} devices linked', async (email, amountOfDevices) => {132 const persons = await browser.call(async() =>await getPersonByEmail(email))133 const person = await find(persons, { type: 'CUSTOMER' })134 const appBundleId = await driver.getCurrentPackage() 135 for (let i = 0; i < amountOfDevices; i++) {136 await browser.call(async() => await logOutAllSessions(person.id))137 await browser.call(async() => await linkAccount(email, uuid(), '192837', `modelo ${i}`, `nombre ${i}`, appBundleId))138 }139})140Given('there is no user registered with DNI {string}', async dni => {141 const persons = await browser.call(async() => await getPersonByDni(dni))142 if (persons.length > 0) {143 persons.forEach(async person => await browser.call(async() => await deletePersonById(person.id)))144 }145})146Given('there is no user registered with mail {string}', async mail => {147 const persons = await browser.call(async() => await getPersonByEmail(mail))148 if (persons.length > 0) {...
driver-e2e-specs.js
Source:driver-e2e-specs.js
...31 driver = null;32 });33 it('should start android session focusing on default pkg and act', async function () {34 driver = await initSession(APIDEMOS_CAPS);35 await driver.getCurrentPackage().should.eventually.equal(APIDEMOS_PACKAGE);36 await driver.getCurrentActivity().should.eventually.equal(APIDEMOS_MAIN_ACTIVITY);37 });38 it('should start android session focusing on custom pkg and act', async function () {39 const caps = amendCapabilities(APIDEMOS_CAPS, {40 'appium:appPackage': APIDEMOS_PACKAGE,41 'appium:appActivity': APIDEMOS_SPLIT_TOUCH_ACTIVITY,42 });43 driver = await initSession(caps);44 await driver.getCurrentPackage().should.eventually.equal(APIDEMOS_PACKAGE);45 await driver.getCurrentActivity().should.eventually.equal(APIDEMOS_SPLIT_TOUCH_ACTIVITY);46 });47 it('should error out for not apk extension', async function () {48 const caps = amendCapabilities(APIDEMOS_CAPS, {49 'appium:app': 'foo',50 'appium:appPackage': APIDEMOS_PACKAGE,51 'appium:appActivity': APIDEMOS_SPLIT_TOUCH_ACTIVITY,52 });53 await initSession(caps).should.eventually.be.rejectedWith(/does not exist or is not accessible/);54 });55 it('should error out for invalid app path', async function () {56 const caps = amendCapabilities(APIDEMOS_CAPS, {57 'appium:app': 'foo.apk',58 'appium:appPackage': APIDEMOS_PACKAGE,59 'appium:appActivity': APIDEMOS_SPLIT_TOUCH_ACTIVITY,60 });61 await initSession(caps).should.eventually.be.rejectedWith(/does not exist or is not accessible/);62 });63 });64 describe('custom adb port', function () {65 let adbPort = 5042;66 let driver;67 beforeEach(async function () {68 await killAndPrepareServer(DEFAULT_ADB_PORT, adbPort);69 });70 afterEach(async function () {71 if (driver) {72 await deleteSession();73 }74 driver = null;75 await killAndPrepareServer(adbPort, DEFAULT_ADB_PORT);76 });77 it('should start android session with a custom adb port', async function () {78 const caps = amendCapabilities(APIDEMOS_CAPS, {79 'appium:adbPort': adbPort,80 'appium:allowOfflineDevices': true,81 });82 driver = await initSession(caps, adbPort);83 await driver.getCurrentPackage().should.eventually.equal(APIDEMOS_PACKAGE);84 await driver.getCurrentActivity().should.eventually.equal(APIDEMOS_MAIN_ACTIVITY);85 });86 });87});88describe('close', function () {89 it('should close application', async function () {90 const driver = await initSession(APIDEMOS_CAPS);91 await driver.closeApp();92 APIDEMOS_PACKAGE.should.not.equal(await driver.getCurrentPackage());93 });...
general-e2e-specs.js
Source:general-e2e-specs.js
...13 await deleteSession();14 });15 describe('startActivity', function () {16 it('should launch a new package and activity', async function () {17 let appPackage = await driver.getCurrentPackage();18 let appActivity = await driver.getCurrentActivity();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({appPackage: startAppPackage, appActivity: startAppActivity});24 let newAppPackage = await driver.getCurrentPackage();25 let newAppActivity = await driver.getCurrentActivity();26 newAppPackage.should.equal(startAppPackage);27 newAppActivity.should.equal(startAppActivity);28 });29 it('should be able to launch activity with custom intent parameter category', async function () {30 let startAppPackage = 'io.appium.android.apis';31 let startAppActivity = 'io.appium.android.apis.app.HelloWorld';32 let startIntentCategory = 'appium.android.intent.category.SAMPLE_CODE';33 await driver.startActivity({appPackage: startAppPackage, appActivity: startAppActivity, intentCategory: startIntentCategory});34 let appActivity = await driver.getCurrentActivity();35 appActivity.should.include('HelloWorld');36 });37 it('should be able to launch activity with dontStopAppOnReset = true', async function () {38 let startAppPackage = 'io.appium.android.apis';39 let startAppActivity = '.os.MorseCode';40 await driver.startActivity({appPackage: startAppPackage, appActivity: startAppActivity});41 let appPackage = await driver.getCurrentPackage();42 let appActivity = await driver.getCurrentActivity();43 appPackage.should.equal(startAppPackage);44 appActivity.should.equal(startAppActivity);45 });46 it('should be able to launch activity with dontStopAppOnReset = false', async function () {47 let startAppPackage = 'io.appium.android.apis';48 let startAppActivity = '.os.MorseCode';49 await driver.startActivity({appPackage: startAppPackage, appActivity: startAppActivity});50 let appPackage = await driver.getCurrentPackage();51 let appActivity = await driver.getCurrentActivity();52 appPackage.should.equal(startAppPackage);53 appActivity.should.equal(startAppActivity);54 });55 });...
camera-screen.js
Source:camera-screen.js
...12 if ( this.isIos() ) {13 await this.click("Take Picture");14 await this.click("Use Photo");15 } else {16 let packageName = await this.driver.getCurrentPackage();17 if ( packageName === "com.sec.android.app.camera") {18 // yuck there isn't an accesssbility label or even button because the UI is in OpenGL19 // this is fragile and will break but for now its OK.20 await this.driver.touchAction([{action: 'tap', x: 1797, y: 545 }]);21 //await this.driver.debug();22 await this.waitForRaw( `android=new UiSelector().resourceId("com.sec.android.app.camera:id/okay")`, "waiting for photo to be taken" )23 await this.clickRaw( `android=new UiSelector().resourceId("com.sec.android.app.camera:id/okay")`);24 } else {25 await this.clickRaw(`android=new UiSelector().resourceId("com.android.camera:id/shutter_button")`); 26 await this.clickRaw(`android=new UiSelector().resourceId("com.android.camera:id/btn_done")`);27 }28 }29 }30}...
button_spec.js
Source:button_spec.js
1var wdio = require("webdriverio");2var assert = require("assert");3async function getElementById(id, driver) {4 const appPackage = await driver.getCurrentPackage();5 const textviewSelector =6 'new UiSelector().resourceId("' + appPackage + ":id/" + id + '")';7 return $("android=" + textviewSelector);8}9describe("Hello button", () => {10 it("should change the text to 'Hello World!'", async () => {11 const paragraph = await getElementById("txtResult", driver);12 let actualText = await paragraph.getText();13 let expectedText = "Hello World!";14 assert.notStrictEqual(15 actualText,16 expectedText,17 "Text should be something else before the button is clicked"18 ); // compare expected value and actula value...
test.js
Source:test.js
1var wdio = require("webdriverio");2var assert = require("assert");3async function getElementById(id, driver) {4 const appPackage = await driver.getCurrentPackage();5 const textviewSelector =6 'new UiSelector().resourceId("' + appPackage + ":id/" + id + '")';7 return $("android=" + textviewSelector);8}9describe("first_test", () => {10 it("TC_01_Sign In To The Account", async () => {11 const paragraph = await getElementById("txtResult", driver);12 let actualText = await paragraph.getText();13 let expectedText = "Hello World!";14 assert.notStrictEqual(15 actualText,16 expectedText,17 "Text should be something else before the button is clicked"18 ); // compare expected value and actula value...
android-create-session.test.js
Source:android-create-session.test.js
...16// });17//18// // Check that we're running the ApiDemos app by checking package and activity19// const activity = await driver.getCurrentActivity();20// const pkg = await driver.getCurrentPackage();21// assert.equal(`${pkg}${activity}`, 'io.appium.android.apis.ApiDemos');22//23// // Quit the session24// await driver.quit();25// });...
getCurrentPackage.js
Source:getCurrentPackage.js
...15 * let package = mob.getCurrentPackage(); // Gets current Android package.16*/17module.exports = async function() {18 await this.helpers.assertContext(this.helpers.contextList.android);19 return await this.driver.getCurrentPackage();...
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.getCurrentPackage().then(function (packageName) {11 console.log(packageName);12});13driver.getCurrentActivity().then(function (activityName) {14 console.log(activityName);15});16driver.getCurrentPackage().then(function (packageName) {17 console.log(packageName);18});19driver.getCurrentActivity().then(function (activityName) {20 console.log(activityName);21});
Using AI Code Generation
1var wd = require('wd');2var driver = wd.promiseChainRemote({3});4driver.init({5}).then(function() {6 driver.getCurrentPackage().then(function(pkg) {7 console.log(pkg);8 });9});
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3 .withCapabilities({4 })5 .build();6driver.getCurrentPackage().then(function (currentPackage) {7 console.log("Current Package: " + currentPackage);8});9driver.quit();
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desired = require('./desired');4var browser = wd.promiseChainRemote('localhost', 4723);5 .init(desired)6 .getCurrentPackage()7 .then(function (pkg) {8 console.log(pkg);9 })10 .fin(function() { return browser.quit(); })11 .done();
Using AI Code Generation
1var wd = require('wd');2var desiredCaps = {3};4var driver = wd.promiseChainRemote('localhost', 4723);5 .init(desiredCaps)6 .getCurrentPackage().then(function(pkg) {7 console.log('Current package is: ' + pkg);8 })9 .quit();
Using AI Code Generation
1import wd from 'wd';2const host = 'localhost';3const port = 4723;4const deviceName = 'Android Emulator';5const packageName = 'com.whatsapp';6const activityName = 'com.whatsapp.Main';7const driver = wd.promiseChainRemote(host, port);8const desiredCaps = {9};10driver.init(desiredCaps)11 .then(() => {12 return driver.getCurrentPackage()13 })14 .then((currentPackage) => {15 console.log('Current Package: ' + currentPackage);16 })17 .catch((err) => {18 console.log(err);19 });
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!!