Best JavaScript code snippet using appium
java.js
Source:java.js
1import Framework from './framework';2import _ from 'lodash';3class JavaFramework extends Framework {4 get language () {5 return 'java';6 }7 wrapWithBoilerplate (code) {8 let [pkg, cls] = (() => {9 if (this.caps.platformName) {10 switch (this.caps.platformName.toLowerCase()) {11 case 'ios': return ['ios', 'IOSDriver'];12 case 'android': return ['android', 'AndroidDriver'];13 default: return ['unknownPlatform', 'UnknownDriver'];14 }15 } else {16 return ['unknownPlatform', 'UnknownDriver'];17 }18 })();19 let capStr = this.indent(Object.keys(this.caps).map((k) => `desiredCapabilities.setCapability(${JSON.stringify(k)}, ${JSON.stringify(this.caps[k])});`).join('\n'), 4);20 return `import io.appium.java_client.MobileElement;21import io.appium.java_client.${pkg}.${cls};22import junit.framework.TestCase;23import org.junit.After;24import org.junit.Before;25import org.junit.Test;26import java.net.MalformedURLException;27import java.net.URL;28import org.openqa.selenium.remote.DesiredCapabilities;29public class SampleTest {30 private ${cls} driver;31 @Before32 public void setUp() throws MalformedURLException {33 DesiredCapabilities desiredCapabilities = new DesiredCapabilities();34${capStr}35 URL remoteUrl = new URL("${this.serverUrl}");36 driver = new ${cls}(remoteUrl, desiredCapabilities);37 }38 @Test39 public void sampleTest() {40${this.indent(code, 4)}41 }42 @After43 public void tearDown() {44 driver.quit();45 }46}47`;48 }49 codeFor_executeScript (/*varNameIgnore, varIndexIgnore, args*/) {50 return `/* TODO implement executeScript */`;51 }52 codeFor_findAndAssign (strategy, locator, localVar, isArray) {53 let suffixMap = {54 xpath: 'XPath',55 'accessibility id': 'AccessibilityId',56 'id': 'Id',57 'class name': 'ClassName',58 'name': 'Name',59 '-android uiautomator': 'AndroidUIAutomator',60 '-android datamatcher': 'AndroidDataMatcher',61 '-android viewtag': 'AndroidViewTag',62 '-ios predicate string': 'IosNsPredicate',63 '-ios class chain': 'IosClassChain',64 };65 if (!suffixMap[strategy]) {66 throw new Error(`Strategy ${strategy} can't be code-gened`);67 }68 if (isArray) {69 return `List<MobileElement> ${localVar} = (MobileElement) driver.findElementsBy${suffixMap[strategy]}(${JSON.stringify(locator)});`;70 } else {71 return `MobileElement ${localVar} = (MobileElement) driver.findElementBy${suffixMap[strategy]}(${JSON.stringify(locator)});`;72 }73 }74 getVarName (varName, varIndex) {75 if (varIndex || varIndex === 0) {76 return `${varName}.get(${varIndex})`;77 }78 return varName;79 }80 codeFor_click (varName, varIndex) {81 return `${this.getVarName(varName, varIndex)}.click();`;82 }83 codeFor_clear (varName, varIndex) {84 return `${this.getVarName(varName, varIndex)}.clear();`;85 }86 codeFor_sendKeys (varName, varIndex, text) {87 return `${this.getVarName(varName, varIndex)}.sendKeys(${JSON.stringify(text)});`;88 }89 codeFor_back () {90 return `driver.navigate().back();`;91 }92 codeFor_tap (varNameIgnore, varIndexIgnore, x, y) {93 return `(new TouchAction(driver)).tap(${x}, ${y}).perform()`;94 }95 codeFor_swipe (varNameIgnore, varIndexIgnore, x1, y1, x2, y2) {96 return `(new TouchAction(driver))97 .press({x: ${x1}, y: ${y1}})98 .moveTo({x: ${x2}: y: ${y2}})99 .release()100 .perform()101 `;102 }103 codeFor_getCurrentActivity () {104 return `String activityName = driver.currentActivity()`;105 }106 codeFor_getCurrentPackage () {107 return `String packageName = driver.currentPackage()`;108 }109 codeFor_startActivity () {110 return `driver.`;111 }112 codeFor_installApp (varNameIgnore, varIndexIgnore, app) {113 return `driver.installApp("${app}");`;114 }115 codeFor_isAppInstalled (varNameIgnore, varIndexIgnore, app) {116 return `boolean isAppInstalled = driver.isAppInstalled("${app}");`;117 }118 codeFor_launchApp () {119 return `driver.launchApp();`;120 }121 codeFor_background (varNameIgnore, varIndexIgnore, timeout) {122 return `driver.runAppInBackground(Duration.ofSeconds(${timeout}));`;123 }124 codeFor_closeApp () {125 return `driver.closeApp();`;126 }127 codeFor_reset () {128 return `driver.reset();`;129 }130 codeFor_removeApp (varNameIgnore, varIndexIgnore, app) {131 return `driver.removeApp("${app}");`;132 }133 codeFor_getStrings (varNameIgnore, varIndexIgnore, language, stringFile) {134 return `Map<String, String> appStrings = driver.getAppStringMap(${language ? `${language}, ` : ''}${stringFile ? `"${stringFile}` : ''});`;135 }136 codeFor_getClipboard () {137 return `String clipboardText = driver.getClipboardText();`;138 }139 codeFor_setClipboard (varNameIgnore, varIndexIgnore, clipboardText) {140 return `driver.setClipboardText("${clipboardText}");`;141 }142 codeFor_pressKeyCode (varNameIgnore, varIndexIgnore, keyCode, metaState, flags) {143 return `driver.pressKeyCode(${keyCode}, ${metaState}, ${flags});`;144 }145 codeFor_longPressKeyCode (varNameIgnore, varIndexIgnore, keyCode, metaState, flags) {146 return `driver.longPressKeyCode(${keyCode}, ${metaState}, ${flags});`;147 }148 codeFor_hideKeyboard () {149 return `driver.hideKeyboard();`;150 }151 codeFor_isKeyboardShown () {152 return `boolean isKeyboardShown = driver.isKeyboardShown();`;153 }154 codeFor_pushFile (varNameIgnore, varIndexIgnore, pathToInstallTo, fileContentString) {155 return `driver.pushFile("${pathToInstallTo}", ${fileContentString})`;156 }157 codeFor_pullFile (varNameIgnore, varIndexIgnore, pathToPullFrom) {158 return `byte[] fileBase64 = driver.pullFile("${pathToPullFrom}");`;159 }160 codeFor_pullFolder (varNameIgnore, varIndexIgnore, folderToPullFrom) {161 return `byte[] fileBase64 = driver.pullFolder("${folderToPullFrom}");`;162 }163 codeFor_toggleAirplaneMode () {164 return `driver.toggleAirplaneMode();`;165 }166 codeFor_toggleData () {167 return `driver.toggleData();`;168 }169 codeFor_toggleWiFi () {170 return `driver.toggleWifi();`;171 }172 codeFor_toggleLocationServices () {173 return `driver.toggleLocationServices();`;174 }175 codeFor_sendSMS (varNameIgnore, varIndexIgnore, phoneNumber, text) {176 return `driver.sendSMS("${phoneNumber}", "${text}");`;177 }178 codeFor_gsmCall (varNameIgnore, varIndexIgnore, phoneNumber, action) {179 return `driver.makeGsmCall("${phoneNumber}", "${action}");`;180 }181 codeFor_gsmSignal (varNameIgnore, varIndexIgnore, signalStrength) {182 return `driver.setGsmSignalStrength("${signalStrength}");`;183 }184 codeFor_gsmVoice (varNameIgnore, varIndexIgnore, state) {185 return `driver.setGsmVoice("${state}");`;186 }187 codeFor_shake () {188 return `driver.shake();`;189 }190 codeFor_lock (varNameIgnore, varIndexIgnore, seconds) {191 return `driver.lockDevice(${seconds});`;192 }193 codeFor_unlock () {194 return `driver.unlockDevice()`;195 }196 codeFor_isLocked () {197 return `boolean isLocked = driver.isDeviceLocked();`;198 }199 codeFor_rotateDevice (varNameIgnore, varIndexIgnore, x, y, radius, rotation, touchCount, duration) {200 return `driver.rotate(new DeviceRotation(${x}, ${y}, ${radius}, ${rotation}, ${touchCount}, ${duration}));`;201 }202 codeFor_getPerformanceData (varNameIgnore, varIndexIgnore, packageName, dataType, dataReadTimeout) {203 return `List<List<Object>> performanceData = driver.getPerformanceData("${packageName}", "${dataType}", ${dataReadTimeout});`;204 }205 codeFor_getPerformanceDataTypes () {206 return `List<String> performanceTypes = driver.getPerformanceDataTypes();`;207 }208 codeFor_touchId (varNameIgnore, varIndexIgnore, match) {209 return `driver.performTouchID(${match});`;210 }211 codeFor_toggleEnrollTouchId (varNameIgnore, varIndexIgnore, enroll) {212 return `driver.toggleTouchIDEnrollment(${enroll});`;213 }214 codeFor_openNotifications () {215 return `driver.openNotifications();`;216 }217 codeFor_getDeviceTime () {218 return `String time = driver.getDeviceTime();`;219 }220 codeFor_fingerprint (varNameIgnore, varIndexIgnore, fingerprintId) {221 return `driver.fingerPrint(${fingerprintId});`;222 }223 codeFor_getSession () {224 return `Map<String, Object> caps = driver.getSessionDetails();`;225 }226 codeFor_setTimeouts (/*varNameIgnore, varIndexIgnore, timeoutsJson*/) {227 return '/* TODO implement setTimeouts */';228 }229 codeFor_getOrientation () {230 return `ScreenOrientation orientation = driver.getOrientation();`;231 }232 codeFor_setOrientation (varNameIgnore, varIndexIgnore, orientation) {233 return `driver.rotate("${orientation}");`;234 }235 codeFor_getGeoLocation () {236 return `Location location = driver.location();`;237 }238 codeFor_setGeoLocation (varNameIgnore, varIndexIgnore, latitude, longitude, altitude) {239 return `driver.setLocation(new Location(${latitude}, ${longitude}, ${altitude}));`;240 }241 codeFor_getLogTypes () {242 return `Set<String> getLogTypes = driver.manage().logs().getAvailableLogTypes();`;243 }244 codeFor_getLogs (varNameIgnore, varIndexIgnore, logType) {245 return `LogEntries logEntries = driver.manage().logs().get("${logType}");`;246 }247 codeFor_updateSettings (varNameIgnore, varIndexIgnore, settingsJson) {248 try {249 let settings = '';250 for (let [settingName, settingValue] of _.toPairs(JSON.parse(settingsJson))) {251 settings += `driver.setSetting("${settingName}", "${settingValue}");\n`;252 }253 return settings;254 } catch (e) {255 return `// Could not parse: ${settingsJson}`;256 }257 }258 codeFor_getSettings () {259 return `Map<String, Object> settings = driver.getSettings();`;260 }261 /*262 codeFor_ REPLACE_ME (varNameIgnore, varIndexIgnore) {263 return `REPLACE_ME`;264 }265 */266 // Web267 codeFor_navigateTo (varNameIgnore, varIndexIgnore, url) {268 return `driver.get("${url}");`;269 }270 codeFor_getUrl () {271 return `String current_url = driver.getCurrentUrl();`;272 }273 codeFor_forward () {274 return `driver.navigate().forward();`;275 }276 codeFor_refresh () {277 return `driver.navigate().refresh();`;278 }279 // Context280 codeFor_getContext () {281 return `driver.getContext()`;282 }283 codeFor_getContexts () {284 return `driver.getContextHandles();`;285 }286 codeFor_switchContext (varNameIgnore, varIndexIgnore, name) {287 return `driver.context("${name}");`;288 }289}290JavaFramework.readableName = 'Java - JUnit';...
js-wdio.js
Source:js-wdio.js
...180 codeFor_performTouchId (varNameIgnore, varIndexIgnore, match) {181 return `await driver.touchId(${match});`;182 }183 codeFor_toggleTouchIdEnrollment (varNameIgnore, varIndexIgnore, enroll) {184 return `await driver.toggleTouchIdEnrollment(${enroll});`;185 }186 codeFor_openNotifications () {187 return `await driver.openNotifications();`;188 }189 codeFor_getDeviceTime () {190 return `let time = await driver.getDeviceTime();`;191 }192 codeFor_fingerprint (varNameIgnore, varIndexIgnore, fingerprintId) {193 return `await driver.fingerprint(${fingerprintId});`;194 }195 codeFor_sessionCapabilities () {196 return `let caps = await driver.session('c8db88a0-47a6-47a1-802d-164d746c06aa');`;197 }198 codeFor_setPageLoadTimeout (varNameIgnore, varIndexIgnore, ms) {...
js-wd.js
Source:js-wd.js
...172 codeFor_performTouchId (varNameIgnore, varIndexIgnore, match) {173 return `await driver.touchId(${match});`;174 }175 codeFor_toggleTouchIdEnrollment (varNameIgnore, varIndexIgnore, enroll) {176 return `await driver.toggleTouchIdEnrollment(${enroll});`;177 }178 codeFor_openNotifications () {179 return `await driver.openNotifications();`;180 }181 codeFor_getDeviceTime () {182 return `let time = await driver.getDeviceTime();`;183 }184 codeFor_fingerprint (varNameIgnore, varIndexIgnore, fingerprintId) {185 return `await driver.fingerprint(${fingerprintId});`;186 }187 codeFor_sessionCapabilities () {188 return `let caps = await driver.sessionCapabilities();`;189 }190 codeFor_setPageLoadTimeout (varNameIgnore, varIndexIgnore, ms) {...
touch-id-e2e-specs.js
Source:touch-id-e2e-specs.js
...24 await killAllSimulators();25 caps = Object.assign(TOUCHIDAPP_CAPS);26 caps.allowTouchIdEnroll = false;27 driver = await initSession(caps);28 await driver.toggleTouchIdEnrollment().should.be.rejectedWith(/enroll touchId/);29 });30 describe('touchID enrollment functional tests applied to TouchId sample app', function () {31 beforeEach(async () => {32 caps = Object.assign(TOUCHIDAPP_CAPS);33 caps.allowTouchIdEnroll = true;34 driver = await initSession(caps);35 await B.delay(2000); // Give the app a couple seconds to open36 });37 it('should not support touchID if not enrolled', async () => {38 let authenticateButton = await driver.elementByName(' Authenticate with Touch ID');39 await authenticateButton.click();40 await driver.elementByName('TouchID not supported').should.eventually.exist;41 });42 it('should accept matching fingerprint if touchID is enrolled or it should not be supported if phone doesn\'t support touchID', async () => {43 await driver.toggleTouchIdEnrollment();44 let authenticateButton = await driver.elementByName(' Authenticate with Touch ID');45 await authenticateButton.click();46 await driver.touchId(true);47 try {48 await driver.elementByName('Authenticated Successfully').should.eventually.exist;49 } catch (ign) {50 await driver.elementByName('TouchID not supported').should.eventually.exist;51 }52 await driver.toggleTouchIdEnrollment();53 });54 it('should reject not matching fingerprint if touchID is enrolled or it should not be supported if phone doesn\'t support touchID', async () => {55 await driver.toggleTouchIdEnrollment();56 let authenticateButton = await driver.elementByName(' Authenticate with Touch ID');57 await authenticateButton.click();58 await driver.touchId(false);59 try {60 await driver.elementByName('Try Again').should.eventually.exist;61 } catch (ign) {62 await driver.elementByName('TouchID not supported').should.eventually.exist;63 }64 await driver.toggleTouchIdEnrollment();65 });66 it('should enroll touchID and accept matching fingerprints then unenroll touchID and not be supported', async () => {67 // Don't enroll68 let authenticateButton = await driver.elementByName(' Authenticate with Touch ID');69 await authenticateButton.click();70 await driver.elementByName('TouchID not supported').should.eventually.exist;71 let okButton = await driver.elementByName('OK');72 await okButton.click();73 await B.delay(1000);74 // Enroll75 await driver.toggleTouchIdEnrollment();76 await authenticateButton.click();77 await driver.touchId(true);78 try {79 await driver.elementByName('Authenticated Successfully').should.eventually.exist;80 } catch (ign) {81 return await driver.elementByName('TouchID not supported').should.eventually.exist;82 }83 okButton = await driver.elementByName('OK');84 await okButton.click();85 await B.delay(1000);86 // Unenroll87 await driver.toggleTouchIdEnrollment();88 authenticateButton = await driver.elementByName(' Authenticate with Touch ID');89 await authenticateButton.click();90 await driver.elementByName('TouchID not supported').should.eventually.exist;91 });92 });...
Using AI Code Generation
1var webdriverio = require('webdriverio'),2 options = {3 desiredCapabilities: {4 }5 };6 .remote(options)7 .init()8 .getTitle().then(function(title) {9 console.log('Title was: ' + title);10 })11 .end();
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder().forBrowser('chrome').build();3driver.manage().window().maximize();4driver.manage().timeouts().implicitlyWait(30000);5driver.findElement(webdriver.By.name('q')).sendKeys('appium');6driver.findElement(webdriver.By.name('btnK')).click();7driver.findElement(webdriver.By.linkText('Appium: Mobile App Automation Made Awesome.')).click();
Using AI Code Generation
1var wd = require('wd');2var driver = wd.promiseChainRemote('localhost', 4723);3driver.init({4}).then(function() {5 return driver.toggleTouchIdEnrollment(true);6}).fin(function() { return driver.quit(); })7 .done();8var wd = require('wd');9var driver = wd.promiseChainRemote('localhost', 4723);10driver.init({11}).then(function() {12 return driver.toggleTouchIdEnrollment(true);13}).fin(function() { return driver.quit(); })14 .done();
Using AI Code Generation
1 withCapabilities({2 build();3driver.toggleTouchIdEnrollment(true).then(function() {4 console.log("Touch ID is now enabled");5});6driver.quit();7var webdriver = require('selenium-webdriver');8var username = process.env.SAUCE_USERNAME;9var accessKey = process.env.SAUCE_ACCESS_KEY;10var driver;11var caps = {12}13 build();14driver.findElement(webdriver.By.name('q')).sendKeys('Appium');15driver.findElement(webdriver.By.name('btnG')).click();16driver.quit();
Using AI Code Generation
1const wdio = require("webdriverio");2const caps = {3};4const client = wdio.remote({5});6async function main() {7 await client.init();8 await client.toggleTouchIdEnrollment(true);9 await client.deleteSession();10}11main();12const wdio = require("webdriverio");13const caps = {14};15const client = wdio.remote({16});17async function main() {18 await client.init();19 await client.toggleTouchIdEnrollment(true);20 await client.deleteSession();21}22main();23const wdio = require("webdriverio");24const caps = {25};26const client = wdio.remote({27});28async function main() {29 await client.init();30 await client.toggleTouchIdEnrollment(true);31 await client.deleteSession();32}33main();
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var asserters = wd.asserters;4var driver = wd.promiseChainRemote("localhost", 4723);5var desired = {6};7driver.init(desired)8 .then(function() {9 return driver.toggleTouchIdEnrollment(true);10 })11 .then(function() {12 return driver.sleep(3000);13 })14 .then(function() {15 return driver.toggleTouchIdEnrollment(false);16 })17 .then(function() {18 return driver.sleep(3000);19 })20 .then(function() {21 return driver.quit();22 })23 .done();24var wd = require('wd');25var assert = require('assert');26var asserters = wd.asserters;27var driver = wd.promiseChainRemote("localhost", 4723);28var desired = {29};30driver.init(desired)31 .then(function() {32 return driver.toggleTouchIdEnrollment(true);33 })34 .then(function() {35 return driver.sleep(3000);36 })37 .then(function() {38 return driver.toggleTouchIdEnrollment(false);39 })40 .then(function() {41 return driver.sleep(3000);42 })43 .then(function() {44 return driver.quit();45 })46 .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!!