How to use uiAutomator.start method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

android.js

Source:android.js Github

copy

Full Screen

1"use strict";2var errors = require('../../server/errors.js')3  , path = require('path')4  , fs = require('fs')5  , Device = require('../device.js')6  , _ = require('underscore')7  , logger = require('../../server/logger.js').get('appium')8  , deviceCommon = require('../common.js')9  , status = require("../../server/status.js")10  , async = require('async')11  , androidController = require('./android-controller.js')12  , androidContextController = require('./android-context-controller.js')13  , androidCommon = require('./android-common.js')14  , androidHybrid = require('./android-hybrid.js')15  , UiAutomator = require('./uiautomator.js')16  , UnknownError = errors.UnknownError;17var Android = function () {18  this.init();19};20_.extend(Android.prototype, Device.prototype);21Android.prototype._deviceInit = Device.prototype.init;22Android.prototype.init = function () {23  this._deviceInit();24  this.appExt = ".apk";25  this.capabilities = {26    platform: 'LINUX'27  , browserName: 'Android'28  , platformVersion: '4.1'29  , webStorageEnabled: false30  , takesScreenshot: true31  , javascriptEnabled: true32  , databaseEnabled: false33  , networkConnectionEnabled: true34  , locationContextEnabled: false35  };36  this.args.devicePort = 4724;37  this.appMd5Hash = null;38  this.args.avd = null;39  this.args.language = null;40  this.args.locale = null;41  this.args.javaVersion = null;42  this.initQueue();43  this.implicitWaitMs = 0;44  this.shuttingDown = false;45  this.adb = null;46  this.uiautomator = null;47  this.uiautomatorRestartOnExit = false;48  this.uiautomatorIgnoreExit = false;49  this.swipeStepsPerSec = 28;50  this.dragStepsPerSec = 40;51  this.asyncWaitMs = 0;52  this.remote = null;53  this.contexts = [];54  this.curContext = this.defaultContext();55  this.didLaunch = false;56  this.launchCb = function () {};57  this.uiautomatorExitCb = function () {};58  this.dataDir = null;59  this.isProxy = false;60  this.proxyHost = null;61  this.proxyPort = null;62  this.proxySessionId = null;63  this.avoidProxy = [64    ['POST', new RegExp('^/wd/hub/session/[^/]+/context')]65  , ['GET', new RegExp('^/wd/hub/session/[^/]+/context')]66  , ['GET', new RegExp('^/wd/hub/session/[^/]+/contexts')]67  , ['POST', new RegExp('^/wd/hub/session/[^/]+/appium')]68  , ['GET', new RegExp('^/wd/hub/session/[^/]+/appium')]69  ];70  // listen for changes to ignoreUnimportantViews71  this.settings.on("update", function (update) {72    if (update.key === "ignoreUnimportantViews") {73      this.setCompressedLayoutHierarchy(update.value, update.callback);74    } else {75      update.callback();76    }77  }.bind(this));78};79Android.prototype._deviceConfigure = Device.prototype.configure;80Android.prototype.noLaunchSetup = function (cb) {81  logger.debug("Setting up Android for 'autoLaunch: false'");82  async.series([83    this.initJavaVersion.bind(this),84    this.initAdb.bind(this),85  ], function (err) { cb(err); });86};87Android.prototype.start = function (cb, onDie) {88  this.launchCb = cb;89  this.uiautomatorExitCb = onDie;90  logger.info("Starting android appium");91  async.series([92    this.initJavaVersion.bind(this),93    this.initAdb.bind(this),94    this.packageAndLaunchActivityFromManifest.bind(this),95    this.initUiautomator.bind(this),96    this.initChromedriverPath.bind(this),97    this.prepareDevice.bind(this),98    this.checkApiLevel.bind(this),99    this.pushStrings.bind(this),100    this.processFromManifest.bind(this),101    this.uninstallApp.bind(this),102    this.installAppForTest.bind(this),103    this.forwardPort.bind(this),104    this.pushAppium.bind(this),105    this.initUnicode.bind(this),106    this.pushSettingsApp.bind(this),107    this.pushUnlock.bind(this),108    function (cb) {this.uiautomator.start(cb);}.bind(this),109    this.wakeUp.bind(this),110    this.unlock.bind(this),111    this.getDataDir.bind(this),112    this.setupCompressedLayoutHierarchy.bind(this),113    this.startAppUnderTest.bind(this),114    this.initAutoWebview.bind(this),115    this.setActualCapabilities.bind(this)116  ], function (err) {117    if (err) {118      this.shutdown(function () {119        this.launchCb(err);120      }.bind(this));121    } else {122      this.didLaunch = true;123      this.launchCb(null, this.proxySessionId);124    }125  }.bind(this));126};127Android.prototype.initUiautomator = function (cb) {128  if (this.uiautomator === null) {129    this.uiautomator = new UiAutomator(this.adb, this.args);130    this.uiautomator.setExitHandler(this.onUiautomatorExit.bind(this));131  }132  return cb();133};134Android.prototype.onLaunch = function (err) {135  var readyToGo = function () {136    this.didLaunch = true;137    this.launchCb();138  }.bind(this);139  var giveUp = function (err) {140    this.shutdown(function () {141      this.launchCb(err);142    }.bind(this));143  }.bind(this);144  if (err) {145    if (this.checkShouldRelaunch(err)) {146      logger.error(err);147      logger.error("Above error isn't fatal, maybe relaunching adb will help....");148      this.adb.waitForDevice(function (err) {149        if (err) return giveUp(err);150        readyToGo();151      });152    } else {153      giveUp(err);154    }155  } else {156    readyToGo();157  }158};159Android.prototype.restartUiautomator = function (cb) {160  async.series([161    this.forwardPort.bind(this)162    , this.uiautomator.start.bind(this.uiautomator)163    , this.setupCompressedLayoutHierarchy.bind(this)164  ], cb);165};166/*167 * Execute an arbitrary function and handle potential ADB disconnection before168 * proceeding169 */170Android.prototype.wrapActionAndHandleADBDisconnect = function (action, ocb) {171  async.series([172    function (cb) {173      this.uiautomatorIgnoreExit = true;174      action(cb);175    }.bind(this)176    , this.adb.restart.bind(this.adb)177    , this.restartUiautomator.bind(this)178  ], function (err) {179    this.uiautomatorIgnoreExit = false;180    ocb(err);181  }.bind(this));182};183Android.prototype.onUiautomatorExit = function () {184  logger.debug("UiAutomator exited");185  var respondToClient = function () {186    this.stopChromedriverProxies(function () {187      this.cleanup();188      if (!this.didLaunch) {189        var msg = "UiAutomator quit before it successfully launched";190        logger.error(msg);191        this.launchCb(new Error(msg));192        return;193      } else if (typeof this.cbForCurrentCmd === "function") {194        var error = new UnknownError("UiAutomator died while responding to " +195                                      "command, please check appium logs!");196        this.cbForCurrentCmd(error, null);197      }198      // make sure appium.js knows we crashed so it can clean up199      this.uiautomatorExitCb();200    }.bind(this));201  }.bind(this);202  if (this.adb) {203    var uninstall = function () {204      logger.debug("Attempting to uninstall app");205      this.uninstallApp(function () {206        this.shuttingDown = false;207        respondToClient();208      }.bind(this));209    }.bind(this);210    if (!this.uiautomatorIgnoreExit) {211      this.adb.ping(function (err, ok) {212        if (ok) {213          uninstall();214        } else {215          logger.debug(err);216          this.adb.restart(function (err) {217            if (err) {218              logger.debug(err);219            }220            if (this.uiautomatorRestartOnExit) {221              this.uiautomatorRestartOnExit = false;222              this.restartUiautomator(function (err) {223                if (err) {224                  logger.debug(err);225                  uninstall();226                }227              }.bind(this));228            } else {229              uninstall();230            }231          }.bind(this));232        }233      }.bind(this));234    } else {235      this.uiautomatorIgnoreExit = false;236    }237  } else {238    logger.debug("We're in uiautomator's exit callback but adb is gone already");239    respondToClient();240  }241};242Android.prototype.checkShouldRelaunch = function (launchErr) {243  if (launchErr.message === null || typeof launchErr.message === 'undefined') {244    logger.error("We're checking if we should relaunch based on something " +245                 "which isn't an error object. Check the codez!");246    return false;247  }248  var msg = launchErr.message.toString();249  var relaunchOn = [250    'Could not find a connected Android device'251    , 'Device did not become ready'252  ];253  var relaunch = false;254  _.each(relaunchOn, function (relaunchMsg) {255    relaunch = relaunch || msg.indexOf(relaunchMsg) !== -1;256  });257  return relaunch;258};259Android.prototype.checkApiLevel = function (cb) {260  this.adb.getApiLevel(function (err, apiLevel) {261    if (err) return cb(err);262    logger.info('Device API level is:', parseInt(apiLevel, 10));263    if (parseInt(apiLevel) < 17) {264      var msg = "Android devices must be of API level 17 or higher. Please change your device to Selendroid or upgrade Android on your device.";265      logger.error(msg); // logs the error when we encounter it266      return cb(new Error(msg)); // send the error up the chain267    }268    cb();269  });270};271Android.prototype.decorateChromeOptions = function (caps) {272  // add options from appium session caps273  if (this.args.chromeOptions) {274    _.each(this.args.chromeOptions, function (val, option) {275      if (typeof caps.chromeOptions[option] === "undefined") {276        caps.chromeOptions[option] = val;277      } else {278        logger.warn("Cannot pass option " + caps.chromeOptions[option] + " because Appium needs it to make chromeDriver work");279      }280    });281  }282  // add device id from adb283  caps.chromeOptions.androidDeviceSerial = this.adb.curDeviceId;284  return caps;285};286Android.prototype.processFromManifest = function (cb) {287  if (!this.args.app) {288    return cb();289  } else { // apk must be local to process the manifest.290    this.adb.processFromManifest(this.args.app, function (err, process) {291      var value = process || this.args.appPackage;292      this.appProcess = value;293      logger.debug("Set app process to: " + this.appProcess);294      cb();295    }.bind(this));296  }297};298Android.prototype.pushStrings = function (cb, language) {299  var outputPath = path.resolve(this.args.tmpDir, this.args.appPackage);300  var remotePath = '/data/local/tmp';301  var stringsJson = 'strings.json';302  this.extractStrings(function (err) {303    if (err) {304      if (!fs.existsSync(this.args.app)) {305        // apk doesn't exist locally so remove old strings.json306        return this.adb.rimraf(remotePath + '/' + stringsJson, function (err) {307          if (err) return cb(new Error("Could not remove old strings"));308          cb();309        });310      } else {311        // if we can't get strings, just dump an empty json and continue312        var remoteFile = remotePath + '/' + stringsJson;313        return this.adb.shell("echo '{}' > " + remoteFile, cb);314      }315    }316    var jsonFile = path.resolve(outputPath, stringsJson);317    this.adb.push(jsonFile, remotePath, function (err) {318      if (err) return cb(new Error("Could not push strings.json"));319      cb();320    });321  }.bind(this), language);322};323Android.prototype.getStrings = function (language, stringFile, cb) {324  if (this.language && this.language === language) {325    // Return last strings326    return cb(null, {327      status: status.codes.Success.code,328      value: this.apkStrings329    });330  }331  // Extract, push and return strings332  return this.pushStrings(function () {333    this.proxy(["updateStrings", {}], function (err, res) {334      if (err || res.status !== status.codes.Success.code) return cb(err, res);335      cb(null, {336        status: status.codes.Success.code,337        value: this.apkStrings338      });339    }.bind(this));340  }.bind(this), language);341};342Android.prototype.pushAppium = function (cb) {343  logger.debug("Pushing appium bootstrap to device...");344  var binPath = path.resolve(__dirname, "..", "..", "..", "build",345      "android_bootstrap", "AppiumBootstrap.jar");346  fs.stat(binPath, function (err) {347    if (err) {348      cb(new Error("Could not find AppiumBootstrap.jar; please run " +349                   "'grunt buildAndroidBootstrap'"));350    } else {351      this.adb.push(binPath, this.remoteTempPath(), cb);352    }353  }.bind(this));354};355Android.prototype.startAppUnderTest = function (cb) {356  this.startApp(this.args, cb);357};358Android.prototype.startApp = function (args, cb) {359  if (args.androidCoverage) {360    this.adb.androidCoverage(args.androidCoverage, args.appWaitPackage,361      args.appWaitActivity, cb);362  } else {363    this.adb.startApp({364      pkg: args.appPackage,365      activity: args.appActivity,366      action: args.intentAction,367      category: args.intentCategory,368      flags: args.intentFlags,369      waitPkg: args.appWaitPackage,370      waitActivity: args.appWaitActivity,371      optionalIntentArguments: args.optionalIntentArguments,372      stopApp: args.stopAppOnReset373    }, cb);374  }375};376Android.prototype.stop = function (cb) {377  if (this.shuttingDown) {378    logger.debug("Already in process of shutting down.");379    return cb();380  }381  this.shuttingDown = true;382  var completeShutdown = function (cb) {383    if (this.adb) {384      this.adb.goToHome(function () {385        this.shutdown(cb);386      }.bind(this));387    } else {388      this.shutdown(cb);389    }390  }.bind(this);391  if (this.args.fullReset) {392    logger.debug("Removing app from device");393    this.uninstallApp(function (err) {394      if (err) {395        // simply warn on error here, because we don't want to stop the shutdown396        // process397        logger.warn(err);398      }399      completeShutdown(cb);400    });401  } else {402    completeShutdown(cb);403  }404};405Android.prototype.cleanup = function () {406  logger.debug("Cleaning up android objects");407  this.adb = null;408  this.uiautomator = null;409  this.shuttingDown = false;410};411Android.prototype.shutdown = function (cb) {412  var next = function () {413    this.stopChromedriverProxies(function () {414      if (this.uiautomator) {415        this.uiautomator.shutdown(function () {416          this.cleanup();417          cb();418        }.bind(this));419      } else {420        this.cleanup();421        cb();422      }423    }.bind(this));424  }.bind(this);425  if (this.adb) {426    this.adb.endAndroidCoverage();427    if (this.args.unicodeKeyboard && this.args.resetKeyboard && this.defaultIME) {428      logger.debug('Resetting IME to \'' + this.defaultIME + '\'');429      this.adb.setIME(this.defaultIME, function (err) {430        if (err) {431          // simply warn on error here, because we don't want to stop the shutdown432          // process433          logger.warn(err);434        }435        if (this.adb) {436          this.adb.stopLogcat(function () {437            next();438          }.bind(this));439        }440      }.bind(this));441    } else {442      this.adb.stopLogcat(function () {443        next();444      }.bind(this));445    }446  } else {447    next();448  }449};450Android.prototype.proxy = deviceCommon.proxy;451Android.prototype.respond = deviceCommon.respond;452Android.prototype.initQueue = function () {453  this.queue = async.queue(function (task, cb) {454    var action = task.action,455        params = task.params;456    this.cbForCurrentCmd = cb;457    if (this.adb && !this.shuttingDown) {458      this.uiautomator.sendAction(action, params, function (response) {459        this.cbForCurrentCmd = null;460        if (typeof cb === 'function') {461          this.respond(response, cb);462        }463      }.bind(this));464    } else {465      this.cbForCurrentCmd = null;466      var msg = "Tried to send command to non-existent Android device, " +467                 "maybe it shut down?";468      if (this.shuttingDown) {469        msg = "We're in the middle of shutting down the Android device, " +470              "so your request won't be executed. Sorry!";471      }472      this.respond({473        status: status.codes.UnknownError.code474      , value: msg475      }, cb);476    }477  }.bind(this), 1);478};479Android.prototype.push = function (elem) {480  this.queue.push({action: elem[0][0], params: elem[0][1] || {}}, elem[1]);481};482Android.prototype.wakeUp = function (cb) {483  // requires an appium bootstrap connection loaded484  logger.debug("Waking up device if it's not alive");485  this.proxy(["wake", {}], cb);486};487Android.prototype.getDataDir = function (cb) {488  this.proxy(["getDataDir", {}], function (err, res) {489    if (err) return cb(err);490    this.dataDir = res.value;491    logger.debug("dataDir set to: " + this.dataDir);492    cb();493  }.bind(this));494};495// Set CompressedLayoutHierarchy on the device based on current settings object496Android.prototype.setupCompressedLayoutHierarchy = function (cb) {497  // setup using cap498  if (_.has(this.args, 'ignoreUnimportantViews')) {499    // set the setting directly on the internal _settings object, this way we don't trigger an update event500    this.settings._settings.ignoreUnimportantViews = this.args.ignoreUnimportantViews;501  }502  if (_.isUndefined(this.getSetting("ignoreUnimportantViews"))) {503    return cb();504  }505  this.setCompressedLayoutHierarchy(this.getSetting("ignoreUnimportantViews"), cb);506};507// Set CompressedLayoutHierarchy on the device508Android.prototype.setCompressedLayoutHierarchy = function (compress, cb) {509  this.proxy(["compressedLayoutHierarchy", {compressLayout: compress}], cb);510};511Android.prototype.waitForActivityToStop = function (cb) {512  this.adb.waitForNotActivity(this.args.appWaitPackage, this.args.appWaitActivity, cb);513};514Android.prototype.setActualCapabilities = function (cb) {515  this.capabilities.deviceName = this.adb.udid || this.adb.curDeviceId;516  this.adb.shell("getprop ro.build.version.release", function (err, version) {517    if (err) {518      logger.warn(err);519    } else {520      logger.debug("Device is at release version " + version);521      this.capabilities.platformVersion = version;522    }523  }.bind(this));524  cb();525};526Android.prototype.resetTimeout = deviceCommon.resetTimeout;527Android.prototype.waitForCondition = deviceCommon.waitForCondition;528Android.prototype.implicitWaitForCondition = deviceCommon.implicitWaitForCondition;529Android.prototype.getSettings = deviceCommon.getSettings;530Android.prototype.updateSettings = deviceCommon.updateSettings;531_.extend(Android.prototype, androidController);532_.extend(Android.prototype, androidContextController);533_.extend(Android.prototype, androidCommon);534_.extend(Android.prototype, androidHybrid);...

Full Screen

Full Screen

chrome.js

Source:chrome.js Github

copy

Full Screen

1"use strict";2var Android = require('./android.js')3  , _ = require('underscore')4  , logger = require('../../server/logger.js').get('appium')5  , status = require('../../server/status.js')6  , deviceCommon = require('../common.js')7  , jwpSuccess = deviceCommon.jwpSuccess8  , async = require('async')9  , ADB = require('./adb.js')10  , UiAutomator = require('./uiautomator.js')11  , Chromedriver = require('./chromedriver.js');12var NATIVE_WIN = "NATIVE_APP";13var WEBVIEW_WIN = "WEBVIEW";14var WEBVIEW_BASE = WEBVIEW_WIN + "_";15var ChromeAndroid = function () {16  this.init();17};18_.extend(ChromeAndroid.prototype, Android.prototype);19ChromeAndroid.prototype._androidInit = Android.prototype.init;20ChromeAndroid.prototype.init = function () {21  this._androidInit();22  this.adb = null;23  this.onDie = null;24  this.setChromedriverMode();25};26ChromeAndroid.prototype.setChromedriverMode = function () {27  logger.info("Set mode: Proxying straight through to Chromedriver");28  this.isProxy = true;29  // when proxying to chromedriver, we need to make sure the context endpoints30  // are trapped by appium for its own purposes31  this.avoidProxy = [32    ['POST', new RegExp('^/wd/hub/session/[^/]+/context')],33    ['GET', new RegExp('^/wd/hub/session/[^/]+/context')],34    ['POST', new RegExp('^/wd/hub/session/[^/]+/touch/perform')],35    ['POST', new RegExp('^/wd/hub/session/[^/]+/touch/multi/perform')]36  ];37};38ChromeAndroid.prototype.setNativeMode = function () {39  logger.info("Set mode: Proxying to Appium Bootstrap");40  this.isProxy = false;41};42ChromeAndroid.prototype.configure = function (args, caps, cb) {43  logger.debug("Looks like we want chrome on android");44  this._deviceConfigure(args, caps);45  var bName = this.args.browserName || "";46  var app = this.appString().toLowerCase() ||47            bName.toString().toLowerCase();48  if (app === "chromium") {49    this.args.androidPackage = "org.chromium.chrome.testshell";50    this.args.androidActivity = "org.chromium.chrome.testshell.Main";51  } else if (app === "chromebeta") {52    this.args.androidPackage = "com.chrome.beta";53    this.args.androidActivity = "com.google.android.apps.chrome.Main";54  } else if (app === "browser") {55    this.args.androidPackage = "com.android.browser";56    this.args.androidActivity = "com.android.browser.BrowserActivity";57  } else {58    this.args.androidPackage = "com.android.chrome";59    this.args.androidActivity = "com.google.android.apps.chrome.Main";60  }61  // don't allow setAndroidArgs to reclobber our androidPackage/activity62  delete this.capabilities.appPackage;63  delete this.capabilities.appActivity;64  this.setAndroidArgs();65  this.args.app = null;66  this.args.proxyPort = this.args.chromeDriverPort;67  cb();68};69ChromeAndroid.prototype.start = function (cb, onDie) {70  this.adb = new ADB(this.args);71  this.uiautomator = new UiAutomator(this.adb, this.args);72  this.uiautomator.setExitHandler(this.onUiautomatorExit.bind(this));73  this.onDie = onDie;74  async.series([75    this.prepareDevice.bind(this),76    this.prepareChromedriver.bind(this),77    this.pushAndUnlock.bind(this),78    this.forwardPort.bind(this),79    this.pushAppium.bind(this),80    this.uiautomator.start.bind(this.uiautomator),81    this.getDataDir.bind(this),82    this.createSession.bind(this)83  ], function (err, results) {84    if (err) return cb(err);85    var sessionId = results[results.length - 1];86    cb(null, sessionId);87  });88};89ChromeAndroid.prototype.prepareChromedriver = function (cb) {90  var chromeArgs = {91    port: this.args.proxyPort92  , executable: this.args.chromedriverExecutable93  , deviceId: this.adb.curDeviceId94  , enablePerformanceLogging: this.args.enablePerformanceLogging95  };96  this.chromedriver = new Chromedriver(chromeArgs,97      this.onChromedriverExit.bind(this));98  this.proxyTo = this.chromedriver.proxyTo.bind(this.chromedriver);99  this.proxyHost = this.chromedriver.proxyHost;100  this.proxyPort = this.chromedriver.proxyPort;101  this.deleteSession = this.chromedriver.deleteSession.bind(this.chromedriver);102  cb();103};104ChromeAndroid.prototype.pushAndUnlock = function (cb) {105  this.pushUnlock(function (err) {106    if (err) return cb(err);107    this.unlock(cb);108  }.bind(this));109};110ChromeAndroid.prototype.createSession = function (cb) {111  var caps = {112    chromeOptions: {113      androidPackage: this.args.appPackage,114      androidActivity: this.args.appActivity115    }116  };117  var knownPackages = ["org.chromium.chrome.testshell", "com.android.chrome",118                       "com.chrome.beta"];119  if (_.contains(knownPackages, this.args.appPackage)) {120    delete caps.chromeOptions.androidActivity;121  }122  this.chromedriver.createSession(caps, cb);123};124ChromeAndroid.prototype.stop = function (cb) {125  this.uiautomator.shutdown(function () {126    this.chromedriver.stop(function (err) {127      if (err) return cb(err);128      this.adb.forceStop(this.args.appPackage, function (err) {129        if (err) return cb(err);130        this.adb.stopLogcat(cb);131      }.bind(this));132    }.bind(this));133  }.bind(this));134};135ChromeAndroid.prototype.onChromedriverExit = function () {136  async.series([137    this.adb.getConnectedDevices.bind(this.adb),138    _.partial(this.adb.forceStop.bind(this.adb), this.args.appPackage)139  ], function (err) {140    if (err) logger.error(err.message);141    this.adb.stopLogcat(this.onDie.bind(this));142  }.bind(this));143};144// since we're in chrome, our default context is not the native mode, but web145ChromeAndroid.prototype.defaultContext = function () {146  return WEBVIEW_BASE + "1";147};148// write a new getContexts function that hard-codes the two available contexts149ChromeAndroid.prototype.getContexts = function (cb) {150  this.contexts = [NATIVE_WIN, this.defaultContext()];151  logger.info("Available contexts: " + this.contexts);152  cb(null, {153    status: status.codes.Success.code154  , value: this.contexts155  });156};157// write a new setContext function that handles starting and stopping of158// chrome mode; the default android context controller method won't work here159// because here we don't need to worry about starting/stopping chromedriver160// itself; it's already on161ChromeAndroid.prototype.setContext = function (name, cb) {162  if (name === null) {163    name = this.defaultContext();164  } else if (name === WEBVIEW_WIN) {165    name = this.defaultContext();166  }167  this.getContexts(function () {168    if (!_.contains(this.contexts, name)) {169      return cb(null, {170        status: status.codes.NoSuchContext.code171      , value: "Context '" + name + "' does not exist"172      });173    }174    if (name === this.curContext) {175      return jwpSuccess(cb);176    }177    if (name.indexOf(WEBVIEW_WIN) !== -1) {178      this.setChromedriverMode();179    } else {180      this.setNativeMode();181    }182    this.curContext = name;183    jwpSuccess(cb);184  }.bind(this));185};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

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.wait(function() {8  return driver.getTitle().then(function(title) {9    return title === 'webdriver - Google Search';10  });11}, 1000);12driver.quit();13var webdriver = require('selenium-webdriver');14var driver = new webdriver.Builder()15    .forBrowser('chrome')16    .build();17driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');18driver.findElement(webdriver.By.name('btnG')).click();19driver.wait(function() {20  return driver.getTitle().then(function(title) {21    return title === 'webdriver - Google Search';22  });23}, 1000);24driver.quit();25var webdriver = require('selenium-webdriver');26var driver = new webdriver.Builder()27    .forBrowser('chrome')28    .build();29driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');30driver.findElement(webdriver.By.name('btnG')).click();31driver.wait(function() {32  return driver.getTitle().then(function(title) {33    return title === 'webdriver - Google Search';34  });35}, 1000);36driver.quit();37var webdriver = require('selenium-webdriver');38var driver = new webdriver.Builder()39    .forBrowser('chrome')40    .build();41driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');42driver.findElement(webdriver.By.name('btnG')).click();43driver.wait(function() {44  return driver.getTitle().then(function(title) {45    return title === 'webdriver - Google Search';46  });47}, 1000);48driver.quit();49var webdriver = require('selenium-webdriver');50var driver = new webdriver.Builder()51    .forBrowser('chrome')52    .build();

Full Screen

Using AI Code Generation

copy

Full Screen

1    build();2driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');3driver.findElement(webdriver.By.name('btnG')).click();4driver.wait(function() {5  return driver.getTitle().then(function(title) {6    return title === 'webdriver - Google Search';7  });8}, 1000);9driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var AppiumAndroidDriver = require('appium-android-driver');2var UiAutomator = AppiumAndroidDriver.UiAutomator;3var uiAutomator = new UiAutomator();4uiAutomator.start(function(err, res) {5    console.log("res : " + res);6});7var AppiumAndroidDriver = require('appium-android-driver');8var UiAutomator = AppiumAndroidDriver.UiAutomator;9var uiAutomator = new UiAutomator();10uiAutomator.stop(function(err, res) {11    console.log("res : " + res);12});13var AppiumAndroidDriver = require('appium-android-driver');14var UiAutomator = AppiumAndroidDriver.UiAutomator;15var uiAutomator = new UiAutomator();16uiAutomator.sendAction('click', 'new UiSelector().text("Settings")', function(err, res) {17    console.log("res : " + res);18});19var AppiumAndroidDriver = require('appium-android-driver');20var UiAutomator = AppiumAndroidDriver.UiAutomator;21var uiAutomator = new UiAutomator();22uiAutomator.sendAction('click', 'new UiSelector().text("Settings")', function(err, res) {23    console.log("res : " + res);24});25var AppiumAndroidDriver = require('appium-android-driver');26var UiAutomator = AppiumAndroidDriver.UiAutomator;27var uiAutomator = new UiAutomator();28uiAutomator.sendAction('click', 'new UiSelector().text("Settings")', function(err, res) {29    console.log("res : " + res);30});31var AppiumAndroidDriver = require('appium-android-driver');32var UiAutomator = AppiumAndroidDriver.UiAutomator;33var uiAutomator = new UiAutomator();34uiAutomator.sendAction('click', 'new UiSelector().text("Settings")', function(err, res) {35    console.log("res : " + res);36});

Full Screen

Using AI Code Generation

copy

Full Screen

1var driver = require('appium-android-driver');2var wd = require('wd');3var path = require('path');4var desiredCapabilities = {5    app: path.resolve(__dirname, 'ApiDemos-debug.apk'),6};7var driver = wd.promiseChainRemote(server);8driver.init(desiredCapabilities).then(function() {9    driver.execute('mobile: uiAutomator', {10        params: {11        }12    });13});14var driver = require('appium-android-driver');15var wd = require('wd');16var path = require('path');17var desiredCapabilities = {18    app: path.resolve(__dirname, 'ApiDemos-debug.apk'),19};20var driver = wd.promiseChainRemote(server);21driver.init(desiredCapabilities).then(function() {22    driver.execute('mobile: uiautomator2', {23        params: {24        }25    });26});27var driver = require('appium-android-driver');28var wd = require('wd');29var path = require('path');30var desiredCapabilities = {31    app: path.resolve(__dirname, 'ApiDemos-debug.apk'),32};33var driver = wd.promiseChainRemote(server);34driver.init(desiredCapabilities).then(function() {35    driver.execute('mobile: espresso', {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var uiAutomator = require('appium-uiautomator');3var assert = require('assert');4var desiredCaps = {5};6var driver = wd.remote('localhost', 4723);7driver.init(desiredCaps, function(err) {8  if (err) throw err;9  driver.elementByClassName('android.widget.EditText', function(err, el) {10    if (err) throw err;11    el.sendKeys('Hello World!', function(err) {12      if (err) throw err;13      driver.elementByClassName('android.widget.TextView', function(err, el) {14        if (err) throw err;15        el.text(function(err, text) {16          if (err) throw err;17          assert.equal(text, 'Hello World!');18          driver.quit();19        });20      });21    });22  });23});24var wd = require('wd');25var uiAutomator = require('appium-uiautomator');26var assert = require('assert');27var desiredCaps = {28};29var driver = wd.remote('localhost', 4723);30driver.init(desiredCaps, function(err) {31  if (err) throw err;32  driver.elementByClassName('android.widget.EditText', function(err, el) {33    if (err) throw err;34    el.sendKeys('Hello World!', function(err) {35      if (err) throw err;36      driver.elementByClassName('android.widget.TextView', function(err, el) {37        if (err) throw err;38        el.text(function(err, text) {39          if (err) throw err;40          assert.equal(text, 'Hello World!');41          driver.quit();42        });43      });44    });45  });46});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var chai = require('chai');4var chaiAsPromised = require('chai-as-promised');5chai.use(chaiAsPromised);6chai.should();7chaiAsPromised.transferPromiseness = wd.transferPromiseness;8var desired = {9};10var driver = wd.promiseChainRemote('localhost', 4723);11  .init(desired)12  .then(function() {13      .elementById('App')14      .click()15      .elementById('Activity')16      .click()17      .elementById('Custom Title')18      .click();19  })20  .then(function() {21      .uiAutomator('uiAutomator.start', {22        component: {23        }24      });25  })26  .then(function() {27      .uiAutomator('uiAutomator.waitForIdle', {28      });29  })30  .then(function() {31      .uiAutomator('uiAutomator.stop');32  })33  .then(function() {34      .uiAutomator('uiAutomator.sendAction', {35      });36  })37  .then(function() {38      .quit();39  })40  .done();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var desired = {3};4var driver = wd.remote('localhost', 4723);5driver.init(desired, function(err) {6    if (err) {7        console.log(err);8        return;9    }10    driver.elementByName('App', function(err, el) {11        if (err) {12            console.log(err);13            return;14        }15        el.click(function(err) {16            if (err) {17                console.log(err);18                return;19            }20            driver.elementByName('Animation', function(err, el) {21                if (err) {22                    console.log(err);23                    return;24                }25                el.click(function(err) {26                    if (err) {27                        console.log(err);28                        return;29                    }30                    driver.elementByName('Bouncing Balls', function(err, el) {31                        if (err) {32                            console.log(err);33                            return;34                        }35                        el.click(function(err) {36                            if (err) {37                                console.log(err);38                                return;39                            }40                            driver.elementByName('Start', function(err, el) {41                                if (err) {42                                    console.log(err);43                                    return;44                                }45                                el.click(function(err) {46                                    if (err) {47                                        console.log(err);48                                        return;49                                    }50                                    driver.sleep(10000, function(err) {51                                        if (err) {52                                            console.log(err);53                                            return;54                                        }55                                        driver.quit();56                                    });57                                });58                            });59                        });60                    });61                });62            });63        });64    });65});

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Android Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful