Best JavaScript code snippet using appium-android-driver
android-helpers.js
Source:android-helpers.js
...247 let apkMd5 = await fs.md5(app);248 let remotePath = helpers.getRemoteApkPath(apkMd5, opts.androidInstallPath);249 let remoteApkExists = await adb.fileExists(remotePath);250 logger.debug("Checking if app is installed");251 let installed = await adb.isAppInstalled(appPackage);252 if (installed && remoteApkExists && fastReset) {253 logger.info("Apk is already on remote and installed, resetting");254 await helpers.resetApp(adb, app, appPackage, fastReset, androidInstallTimeout);255 } else if (!installed || (!remoteApkExists && fastReset)) {256 if (!installed) {257 logger.info("Apk is not yet installed");258 } else {259 logger.info("Apk was already installed but not from our remote path");260 }261 logger.info(`${installed ? 'Re' : ''}installing apk from remote`);262 await adb.mkdir(REMOTE_TEMP_PATH);263 logger.info("Clearing out any existing remote apks with the same hash");264 await helpers.removeRemoteApks(adb, [apkMd5]);265 if (!remoteApkExists) {266 // push from local to remote267 logger.info(`Pushing ${appPackage} to device. Will wait up to ${androidInstallTimeout} ` +268 `milliseconds before aborting`);269 await adb.push(app, remotePath, {timeout: androidInstallTimeout});270 }271 // Next, install from the remote path. This can be flakey. If it doesn't272 // work, clear out any cached apks, re-push from local, and try again273 await helpers.reinstallRemoteApk(adb, app, appPackage, remotePath, androidInstallTimeout);274 }275};276helpers.removeRemoteApks = async function (adb, exceptMd5s = null) {277 logger.debug("Removing any old apks");278 if (exceptMd5s) {279 logger.debug(`Except ${JSON.stringify(exceptMd5s)}`);280 } else {281 exceptMd5s = [];282 }283 let apks = await adb.ls(`${REMOTE_TEMP_PATH}/*.apk`);284 if (apks.length < 1) {285 logger.debug("No apks to examine");286 return;287 }288 apks = apks.filter((apk) => {289 for (let md5 of exceptMd5s) {290 return apk.indexOf(md5) === -1;291 }292 });293 for (let apk of apks) {294 logger.info(`Will remove ${apk}`);295 await adb.shell(['rm', '-f', apk]);296 }297};298helpers.initUnicodeKeyboard = async function (adb) {299 logger.debug('Enabling Unicode keyboard support');300 logger.debug("Pushing unicode ime to device...");301 if (!await adb.isAppInstalled('io.appium.android.ime')) {302 await adb.install(unicodeIMEPath, false);303 }304 // get the default IME so we can return back to it later if we want305 let defaultIME = await adb.defaultIME();306 logger.debug(`Unsetting previous IME ${defaultIME}`);307 const appiumIME = 'io.appium.android.ime/.UnicodeIME';308 logger.debug(`Setting IME to '${appiumIME}'`);309 await adb.enableIME(appiumIME);310 await adb.setIME(appiumIME);311 return defaultIME;312};313helpers.setMockLocationApp = async function (adb, app) {314 try {315 if (await adb.getApiLevel() < 23) {316 await adb.shell(['settings', 'put', 'secure', 'mock_location', '1']);317 } else {318 await adb.shell(['appops', 'set', app, 'android:mock_location', 'allow']);319 }320 } catch (err) {321 logger.warn(`Unable to set mock location for app '${app}': ${err.message}`);322 }323};324helpers.installHelperApp = async function (adb, apkPath, packageId, appName) {325 try {326 await adb.installOrUpgrade(apkPath, packageId);327 } catch (err) {328 logger.warn(`Ignored error while installing Appium ${appName} helper: ` +329 `'${err.message}'. Manually uninstalling the application ` +330 `with package id '${packageId}' may help. Expect some Appium ` +331 `features may not work as expected unless this problem is ` +332 `fixed.`);333 }334};335helpers.pushSettingsApp = async function (adb, throwError = false) {336 if (!(await adb.isAppInstalled(SETTINGS_HELPER_PKG_ID))) { // never update, added by shawn337 logger.debug("Pushing settings apk to device...");338 await helpers.installHelperApp(adb, settingsApkPath, SETTINGS_HELPER_PKG_ID, 'Settings');339 try {340 await adb.grantAllPermissions(SETTINGS_HELPER_PKG_ID);341 } catch (err) {342 // errors are expected there, since the app contains non-changeable permissons343 }344 }345 // lauch io.appium.settings app due to settings failing to be set346 // if the app is not launched prior to start the session on android 7+347 // see https://github.com/appium/appium/issues/8957348 try {349 if (!(await adb.processExists(SETTINGS_HELPER_PKG_ID))) {350 let startOpts = {351 pkg: SETTINGS_HELPER_PKG_ID,352 activity: SETTINGS_HELPER_PKG_ACTIVITY,353 action: "android.intent.action.MAIN",354 category: "android.intent.category.LAUNCHER",355 flags: "0x10200000",356 stopApp: false357 };358 await adb.startApp(startOpts);359 }360 } catch (err) {361 logger.warn(`Failed to launch settings app: ${err.message}`);362 if (throwError) {363 throw err;364 }365 }366};367helpers.pushUnlock = async function (adb) {368 if (!(await adb.isAppInstalled(SETTINGS_HELPER_PKG_ID))) { // never update, added by shawn369 logger.debug("Pushing unlock helper app to device...");370 await helpers.installHelperApp(adb, unlockApkPath, UNLOCK_HELPER_PKG_ID, 'Unlock');371 }372};373// pushStrings method extracts string.xml and converts it to string.json and pushes374// it to /data/local/tmp/string.json on for use of bootstrap375// if app is not present to extract string.xml it deletes remote strings.json376// if app does not have strings.xml we push an empty json object to remote377helpers.pushStrings = async function (language, adb, opts) {378 let remotePath = '/data/local/tmp';379 let stringsJson = 'strings.json';380 let stringsTmpDir = path.resolve(opts.tmpDir, opts.appPackage);381 try {382 logger.debug('Extracting strings from apk', opts.app, language, stringsTmpDir);...
adb-commands-e2e-specs.js
Source:adb-commands-e2e-specs.js
...147 if (deviceApiLevel < 23) {148 //test should skip if the device API < 23149 this.skip();150 }151 let isInstalled = await adb.isAppInstalled('io.appium.android.apis');152 if (isInstalled) {153 await adb.uninstallApk('io.appium.android.apis');154 }155 });156 it('should install and grant all permission', async () => {157 let apiDemos = path.resolve(rootDir, 'test',158 'fixtures', 'ApiDemos-debug.apk');159 await adb.install(apiDemos);160 (await adb.isAppInstalled('io.appium.android.apis')).should.be.true;161 await adb.grantAllPermissions('io.appium.android.apis');162 let requestedPermissions = await adb.getReqPermissions('io.appium.android.apis');163 expect(await adb.getGrantedPermissions('io.appium.android.apis')).to.have.members(requestedPermissions);164 });165 it('should revoke permission', async () => {166 await adb.revokePermission('io.appium.android.apis', 'android.permission.RECEIVE_SMS');167 expect(await adb.getGrantedPermissions('io.appium.android.apis')).to.not.have.members(['android.permission.RECEIVE_SMS']);168 });169 it('should grant permission', async () => {170 await adb.grantPermission('io.appium.android.apis', 'android.permission.RECEIVE_SMS');171 expect(await adb.getGrantedPermissions('io.appium.android.apis')).to.include.members(['android.permission.RECEIVE_SMS']);172 });173 });174 describe('push file', function () {...
apk-utils-e2e-specs.js
Source:apk-utils-e2e-specs.js
...21 before(async () => {22 adb = await ADB.createADB();23 });24 it('should be able to check status of third party app', async () => {25 (await adb.isAppInstalled('com.android.phone')).should.be.true;26 });27 it('should be able to install/remove app and detect its status', async () => {28 (await adb.isAppInstalled('foo')).should.be.false;29 await adb.install(contactManagerPath);30 (await adb.isAppInstalled('com.example.android.contactmanager')).should.be.true;31 (await adb.uninstallApk('com.example.android.contactmanager')).should.be.true;32 (await adb.isAppInstalled('com.example.android.contactmanager')).should.be.false;33 (await adb.uninstallApk('com.example.android.contactmanager')).should.be.false;34 await adb.rimraf(deviceTempPath + 'ContactManager.apk');35 await adb.push(contactManagerPath, deviceTempPath);36 await adb.installFromDevicePath(deviceTempPath + 'ContactManager.apk');37 });38 describe('startUri', async () => {39 it('should be able to start a uri', async () => {40 await adb.goToHome();41 let res = await adb.getFocusedPackageAndActivity();42 res.appPackage.should.not.equal('com.android.contacts');43 await adb.install(contactManagerPath);44 await adb.startUri('content://contacts/people', 'com.android.contacts');45 await retryInterval(10, 500, async () => {46 res = await adb.shell(['dumpsys', 'window', 'windows']);...
app-management.js
Source:app-management.js
...15 * @param {string} appId - Application package identifier16 * @returns {boolean} true if the app is installed17 */18commands.isAppInstalled = async function isAppInstalled (appId) {19 return await this.adb.isAppInstalled(appId);20};21/**22 * Queries the current state of the app.23 *24 * @param {string} appId - Application package identifier25 * @returns {number} The corresponding constant, which describes26 * the current application state:27 * 0 - is the app is not installed28 * 1 - if the app is installed, but is not running29 * 3 - if the app is running in the background30 * 4 - if the app is running in the foreground31 */32commands.queryAppState = async function queryAppState (appId) {33 log.info(`Querying the state of '${appId}'`);34 if (!await this.adb.isAppInstalled(appId)) {35 return APP_STATE_NOT_INSTALLED;36 }37 if (!await this.adb.processExists(appId)) {38 return APP_STATE_NOT_RUNNING;39 }40 for (const line of (await this.adb.dumpWindows()).split('\n')) {41 if (line.includes(appId) && (line.includes('mCurrentFocus') || line.includes('mFocusedApp'))) {42 return APP_STATE_RUNNING_IN_FOREGROUND;43 }44 }45 return APP_STATE_RUNNING_IN_BACKGROUND;46};47/**48 * Activates the given application or launches it if necessary....
selendroid.js
Source:selendroid.js
...38 await this.adb.uninstallApk(this.modServerPkg);39 }40 }41 async installModifiedServer () {42 let installed = await this.adb.isAppInstalled(this.modServerPkg);43 if (!installed) {44 await this.adb.install(this.modServerPath);45 }46 }47 async buildNewModServer () {48 logger.info(`Repackaging selendroid for: '${this.appPackage}'`);49 let packageTmpDir = path.resolve(this.tmpDir, this.appPackage);50 let newManifestPath = path.resolve(this.tmpDir, 'AndroidManifest.xml');51 logger.info(`Creating new manifest: '${newManifestPath}'`);52 await fs.mkdir(packageTmpDir);53 await fs.copyFile(SE_MANIFEST_PATH, newManifestPath);54 await this.adb.initAapt(); // TODO this should be internal to adb55 await this.adb.compileManifest(newManifestPath, this.modServerPkg,56 this.appPackage);...
android-helper-e2e-specs.js
Source:android-helper-e2e-specs.js
...22 describe('installApk', function () {23 it('installs an apk by pushing it to the device then installing it from within', async function () {24 this.timeout(MOCHA_TIMEOUT);25 await retryInterval(10, 500, async function () {26 if (await adb.isAppInstalled(opts.appPackage)) {27 // this sometimes times out on Travis, so retry28 await adb.uninstallApk(opts.appPackage);29 }30 });31 await adb.isAppInstalled(opts.appPackage).should.eventually.be.false;32 await helpers.installApk(adb, opts);33 await adb.isAppInstalled(opts.appPackage).should.eventually.be.true;34 });35 });36 describe('ensureDeviceLocale @skip-ci', function () {37 after(async function () {38 await helpers.ensureDeviceLocale(adb, 'en', 'US');39 });40 it('should set device language and country', async function () {41 await helpers.ensureDeviceLocale(adb, 'fr', 'FR');42 if (await adb.getApiLevel() < 23) {43 await adb.getDeviceLanguage().should.eventually.equal('fr');44 await adb.getDeviceCountry().should.eventually.equal('FR');45 } else {46 await adb.getDeviceLocale().should.eventually.equal('fr-FR');47 }...
url-e2e-specs.js
Source:url-e2e-specs.js
...14 let urlId = 'com.android.browser:id/url';15 before(async function () {16 if (process.env.TRAVIS) return this.skip(); // eslint-disable-line curly17 let adb = new ADB();18 if (!await adb.isAppInstalled('com.android.browser')) {19 if (!await adb.isAppInstalled('com.android.chrome')) {20 throw new Error('Neither default browser nor chrome available');21 }22 // `browser` is not available, so use `Chrome`23 caps.browserName = 'Chrome';24 urlId = 'com.android.chrome:id/url_bar';25 }26 driver = new AndroidDriver();27 await driver.createSession(caps);28 });29 after(async function () {30 if (driver) {31 await driver.deleteSession();32 }33 });...
adb-emu-commands-e2e-specs.js
Source:adb-emu-commands-e2e-specs.js
...20 this.skip();21 }22 });23 it('fingerprint should open the secret activity on emitted valid finger touch event', async () => {24 if (await adb.isAppInstalled(pkg)) {25 await adb.forceStop(pkg);26 await adb.uninstallApk(pkg);27 }28 await adb.install(fingerprintPath);29 await adb.startApp({pkg, activity});30 await sleep(500);31 let app = await adb.getFocusedPackageAndActivity();32 app.appActivity.should.equal(activity);33 await adb.fingerprint(1111);34 await sleep(2500);35 app = await adb.getFocusedPackageAndActivity();36 app.appActivity.should.equal(secretActivity);37 });38});
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.findElement(By.name('q')).sendKeys('webdriver');11driver.findElement(By.name('btnG')).click();12driver.wait(until.titleIs('webdriver - Google Search'), 1000);13driver.quit();14driver.findElement(By.name('q')).sendKeys('webdriver');15driver.findElement(By.name('btnG')).click();16driver.wait(until.titleIs('webdriver - Google Search'), 1000);17driver.quit();18driver.findElement(By.name('q')).sendKeys('webdriver');19driver.findElement(By.name('btnG')).click();20driver.wait(until.titleIs('webdriver - Google Search'), 1000);21driver.quit();22driver.findElement(By.name('q')).sendKeys('webdriver');23driver.findElement(By.name('btnG')).click();24driver.wait(until.titleIs('webdriver - Google Search'), 1000);25driver.quit();26driver.findElement(By.name('q')).sendKeys('webdriver');27driver.findElement(By.name('btnG')).click();28driver.wait(until.titleIs('webdriver - Google Search'), 1000);29driver.quit();30driver.findElement(By.name('q')).sendKeys('webdriver');31driver.findElement(By.name('btnG')).click();32driver.wait(until.titleIs('webdriver - Google Search'), 1000);33driver.quit();
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();10var webdriver = require('selenium-webdriver'),11 until = webdriver.until;12var driver = new webdriver.Builder()13 .forBrowser('chrome')14 .build();15driver.findElement(By.name('q')).sendKeys('webdriver');16driver.findElement(By.name('btnG')).click();17driver.wait(until.titleIs('webdriver - Google Search'), 1000);18driver.quit();19var webdriver = require('selenium-webdriver'),20 until = webdriver.until;21var driver = new webdriver.Builder()22 .forBrowser('chrome')23 .build();24driver.findElement(By.name('q')).sendKeys('webdriver');25driver.findElement(By.name('btnG')).click();26driver.wait(until.titleIs('webdriver - Google Search'), 1000);27driver.quit();28var webdriver = require('selenium-webdriver'),29 until = webdriver.until;30var driver = new webdriver.Builder()31 .forBrowser('chrome')32 .build();33driver.findElement(By.name('q')).sendKeys('webdriver');34driver.findElement(By.name('btnG')).click();35driver.wait(until.titleIs('webdriver - Google Search'), 1000);36driver.quit();37var webdriver = require('selenium-webdriver'),38 until = webdriver.until;39var driver = new webdriver.Builder()40 .forBrowser('chrome')41 .build();42driver.findElement(By.name('q')).sendKeys('webdriver');43driver.findElement(By.name('btnG')).click();44driver.wait(until.titleIs('webdriver - Google Search'),
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var By = webdriver.By;3var until = webdriver.until;4var AndroidDriver = require('appium-android-driver');5var ADB = AndroidDriver.ADB;6var adb = new ADB();7var driver;8var desiredCapabilities = {9};10driver = new webdriver.Builder()
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var asserters = wd.asserters;4var should = require('should');5var desired = {6};7var driver = wd.promiseChainRemote("localhost", 4723);8 .init(desired)9 .then(function () {10 return driver.isAppInstalled('com.example.android.contactmanager');11 })12 .then(function (isInstalled) {13 console.log('App installed: ' + isInstalled);14 })15 .fin(function () {16 return driver.quit();17 })18 .done();
Using AI Code Generation
1describe('Appium Android Driver', function() {2 it('should check if App installed', async function() {3 const isAppInstalled = await driver.adb.isAppInstalled('com.android.chrome');4 console.log('isAppInstalled: ' + isAppInstalled);5 });6});7exports.config = {8 capabilities: [{9 'goog:chromeOptions': {10 }11 }],12 mochaOpts: {13 }14};15{16 "scripts": {17 },18 "dependencies": {19 }20}21{22 "packages": {23 "": {
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var AndroidDriver = require("appium-android-driver");4var desired = {5};6 .init(desired)7 .then(function () {8 return driver.isAppInstalled("com.example.app");9 })10 .then(function (isInstalled) {11 if (!isInstalled) {12 return driver.installApp("/path/to/your/app.apk");13 }14 })15 .fin(function () { return driver.quit(); })16 .done();
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var appium = require('appium');4var driver = wd.promiseChainRemote("localhost", 4723);5var desiredCaps = {6};7 .init(desiredCaps)8 .then(function() {9 return driver.isAppInstalled("io.appium.android.apis");10 })11 .then(function(isInstalled) {12 if(!isInstalled) {13 }14 })15 .then(function() {16 return driver.startActivity("io.appium.android.apis", ".ApiDemos");17 })18 .then(function() {19 return driver.quit();20 })21 .done();
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!!