Best JavaScript code snippet using appium
mobile_driver.js
Source:mobile_driver.js
...491 }492 }493 async waitForCookie(title) {494 let logCookie = '';495 return this.driver.allCookies().then((cookies) => {496 let isCookiePresent = false;497 logCookie = JSON.stringify(cookies);498 let targetCookieValue = "";499 cookies.forEach((cookie) => {500 if (cookie.name === title) {501 isCookiePresent = true;502 targetCookieValue = cookie.value;503 }504 });505 //check if cookie exists; If yes, return the cookie value506 if (isCookiePresent) {507 return targetCookieValue;508 } else {509 throw new Error(`Cookie ${title} not found`);510 }511 }).catch(async (error) => {512 error.message = `Error occurred in driver.waitForCookie("${title}")\n` + error.message;513 error.message = error.message + `\nLast checked cookies are: "${logCookie}"`;514 await this.processAndThrowError(error, new Error().stack);515 });516 }517 async getCookie(title) {518 const cookies = await this.driver.allCookies();519 const cookie = cookies[title];520 if (cookie !== null) {521 return cookie.value;522 } else {523 return null;524 }525 }526 async waitForCookieToClear(title) {527 const isCookiePresent = (async function (title) {528 const cookies = await this.driver.allCookies();529 if (cookies[title]) {530 return false;531 } else {532 return true;533 }534 }).bind(this);535 return await this.driver.waitFor(asserters.jsCondition(await isCookiePresent(title)), this.timeout)536 .catch(async error => {537 error.message = `Error occurred in driver.waitForCookieToClear("${title}")\n` + error.message;538 await this.processAndThrowError(error, new Error().stack);539 });540 }541 async waitForCookieToEqual(title, value) {542 let logCookie = '';543 const getCookieValue = (async function (title) {544 const cookieValue = await this.waitForCookie(title);545 logCookie = cookieValue;546 return logCookie;547 }).bind(this);548 await this.driver549 .waitFor(asserters.jsCondition((await getCookieValue(title)) === value), this.timeout)550 .catch(async error => {551 error.message = `Error occurred in driver.waitForCookieToBeEqual("${title}", "${value}")\n` + error.message;552 error.message = error.message + `\nLast checked cookie value: "${logCookie}"`;553 await this.processAndThrowError(error, new Error().stack);554 });555 }556 async getContexts() {557 return await this.driver.contexts();558 }559 async setContext(context) {560 await this.driver.context(context);561 }562 async getElementCoordinates(strategy, locator) {563 strategy = strategyMapping(strategy);564 let element = await this.driver.waitForElements(strategy, locator, this.timeout);565 return await this.driver.getLocation(element[0]);566 }567 async swipeByCoordinates(startX, startY, endX, endY) {568 let action = new wd.TouchAction();569 await action.press({570 x: startX,571 y: startY572 })573 .wait(500)574 .moveTo({575 x: endX,576 y: endY577 })578 .release();579 await this.driver.performTouchAction(action);580 }581 async tapByCoordinates(x, y) {582 await this.driver.execute("mobile:tap", {583 x: x,584 y: y585 });586 }587 // =============================================================================588 // Private methods. Do not expose in d.ts589 // =============================================================================590 async processAndThrowError(error, errorStack) {591 if (!error.message.includes('Cookies')) {592 try {593 const cookiesFromDriver = await this.driver.allCookies();594 error.message += `\nCookies from 'this.driver.allCookies()' cmd: ${JSON.stringify(cookiesFromDriver)}`;595 } catch (error) {596 error.message += `\nCookies: error getting cookies: ${error}`;597 }598 }599 if (!error.message.includes('Current URL')) {600 const currentUrl = await this.driver.url();601 error.message += `\nCurrent URL : ${currentUrl}`;602 // check if js url is the same as the one retrieved by driver603 const jsUrl = await this.driver.execute(`return window.location.toString();`);604 if (currentUrl !== jsUrl) {605 error.message += `\nJS URL : ${jsUrl}`;606 }607 const time = moment().format('YYYY-MM-DD hh:mm:sssss');608 error.message += `\nCurrent Time: ${time}`;...
safari-basic-e2e-specs.js
Source:safari-basic-e2e-specs.js
...347 it('should be able to get cookies for a page with none', async function () {348 await openPage(driver, GUINEA_PIG_IFRAME_PAGE);349 await driver.deleteAllCookies();350 await retryInterval(5, 1000, async function () {351 await driver.allCookies().should.eventually.have.length(0);352 });353 });354 });355 describe('within webview', function () {356 describe('insecure', function () {357 beforeEach(async function () {358 await openPage(driver, GUINEA_PIG_PAGE);359 await driver.deleteCookie(newCookie.name);360 });361 it('should be able to get cookies for a page', async function () {362 const cookies = await driver.allCookies();363 cookies.length.should.equal(2);364 doesIncludeCookie(cookies, oldCookie1);365 doesIncludeCookie(cookies, oldCookie2);366 });367 it('should be able to set a cookie for a page', async function () {368 await driver.setCookie(newCookie);369 const cookies = await driver.allCookies();370 doesIncludeCookie(cookies, newCookie);371 // should not clobber old cookies372 doesIncludeCookie(cookies, oldCookie1);373 doesIncludeCookie(cookies, oldCookie2);374 });375 it('should be able to set a cookie with expiry', async function () {376 const expiredCookie = Object.assign({}, newCookie, {377 expiry: parseInt(Date.now() / 1000, 10) - 1000, // set cookie in past378 name: 'expiredcookie',379 });380 let cookies = await driver.allCookies();381 doesNotIncludeCookie(cookies, expiredCookie);382 await driver.setCookie(expiredCookie);383 cookies = await driver.allCookies();384 // should not include cookie we just added because of expiry385 doesNotIncludeCookie(cookies, expiredCookie);386 // should not clobber old cookies387 doesIncludeCookie(cookies, oldCookie1);388 doesIncludeCookie(cookies, oldCookie2);389 await driver.deleteCookie(expiredCookie.name);390 });391 it('should be able to delete one cookie', async function () {392 await driver.setCookie(newCookie);393 let cookies = await driver.allCookies();394 doesIncludeCookie(cookies, newCookie);395 await driver.deleteCookie(newCookie.name);396 cookies = await driver.allCookies();397 doesNotIncludeCookie(cookies, newCookie);398 doesIncludeCookie(cookies, oldCookie1);399 doesIncludeCookie(cookies, oldCookie2);400 });401 it('should be able to delete all cookies', async function () {402 await driver.setCookie(newCookie);403 let cookies = await driver.allCookies();404 doesIncludeCookie(cookies, newCookie);405 await driver.deleteAllCookies();406 cookies = await driver.allCookies();407 cookies.length.should.equal(0);408 doesNotIncludeCookie(cookies, oldCookie1);409 doesNotIncludeCookie(cookies, oldCookie2);410 });411 describe('native context', function () {412 const notImplementedRegExp = /Method is not implemented/;413 let context;414 beforeEach(async function () {415 context = await driver.currentContext();416 await driver.context('NATIVE_APP');417 });418 afterEach(async function () {419 if (context) {420 await driver.context(context);421 }422 });423 it('should reject all functions', async function () {424 await driver.setCookie(newCookie).should.eventually.be.rejectedWith(notImplementedRegExp);425 await driver.allCookies().should.eventually.be.rejectedWith(notImplementedRegExp);426 await driver.deleteCookie(newCookie.name).should.eventually.be.rejectedWith(notImplementedRegExp);427 await driver.deleteAllCookies().should.eventually.be.rejectedWith(notImplementedRegExp);428 });429 });430 });431 describe('secure', function () {432 /*433 * secure cookie tests are in `./safari-ssl-e2e-specs.js`434 */435 });436 });437 });438 });439 describe('safariIgnoreFraudWarning', function () {...
Appium JS commands.js
Source:Appium JS commands.js
...615//Retrieve all cookies visible to the current page (Web context only)616// webdriver.io example617let cookies = driver.getCookies();618// wd example619let cookies = await driver.allCookies();620//Set a cookie (Web context only)621// webdriver.io example622driver.setCookies([{623 name: 'myCookie',624 value: 'some content'625 }]);626 627 // wd example628 let cookies = await driver.setCookie({name: 'foo', value: 'bar'});629 630//Delete the cookie with the given name (Web context only)631// webdriver.io example632driver.deleteCookies("cookie_name");633// wd example...
cookies-base.js
Source:cookies-base.js
...12 describe('within iframe webview', function () {13 it('should be able to get cookies for a page with none', function (done) {14 loadWebView(desired, driver, testEndpoint(desired) + 'iframes.html',15 "Iframe guinea pig").then(function () {16 return driver.allCookies().should.eventually.have.length(0);17 }).nodeify(done);18 });19 });20 describe('within webview', function () {21 // TODO: investigate why we need that22 function _ignoreEncodingBug(value) {23 if (isChrome(desired)) {24 console.warn('Going round android bug: whitespace in cookies.');25 return encodeURI(value);26 } else return value;27 }28 beforeEach(function (done) {29 loadWebView(desired, driver).nodeify(done);30 });...
safari-cookie-e2e-specs.js
Source:safari-cookie-e2e-specs.js
...24 it('should be able to get cookies for a page with none', async () => {25 await driver.get(GUINEA_PIG_IFRAME_PAGE);26 await driver.deleteAllCookies();27 await driver.get(GUINEA_PIG_IFRAME_PAGE);28 let cookies = await driver.allCookies();29 cookies.should.have.length(0);30 });31 });32 describe('within webview', function () {33 const newCookie = {34 name: 'newcookie',35 value: 'i am new here'36 };37 const oldCookie1 = {38 name: 'guineacookie1',39 value: 'i am a cookie value'40 };41 const oldCookie2 = {42 name: 'guineacookie2',43 value: 'cookié2'44 };45 let doesIncludeCookie = function (cookies, cookie) {46 cookies.map((c) => c.name).should.include(cookie.name);47 cookies.map((c) => c.value).should.include(cookie.value);48 };49 let doesNotIncludeCookie = function (cookies, cookie) {50 cookies.map((c) => c.name).should.not.include(cookie.name);51 cookies.map((c) => c.value).should.not.include(cookie.value);52 };53 beforeEach(async () => {54 await driver.get(GUINEA_PIG_PAGE);55 });56 it('should be able to get cookies for a page', async () => {57 let cookies = await driver.allCookies();58 cookies.length.should.equal(2);59 doesIncludeCookie(cookies, oldCookie1);60 doesIncludeCookie(cookies, oldCookie2);61 });62 it('should be able to set a cookie for a page', async () => {63 await driver.deleteCookie(newCookie.name);64 let cookies = await driver.allCookies();65 doesNotIncludeCookie(cookies, newCookie);66 await driver.setCookie(newCookie);67 cookies = await driver.allCookies();68 doesIncludeCookie(cookies, newCookie);69 // should not clobber old cookies70 doesIncludeCookie(cookies, oldCookie1);71 doesIncludeCookie(cookies, oldCookie2);72 });73 it('should be able to set a cookie with expiry', async () => {74 let expiredCookie = _.defaults({75 expiry: parseInt(Date.now() / 1000, 10) - 1000 // set cookie in past76 }, newCookie);77 await driver.deleteCookie(expiredCookie.name);78 let cookies = await driver.allCookies();79 doesNotIncludeCookie(cookies, expiredCookie);80 await driver.setCookie(expiredCookie);81 cookies = await driver.allCookies();82 // should not include cookie we just added because of expiry83 doesNotIncludeCookie(cookies, expiredCookie);84 // should not clobber old cookies85 doesIncludeCookie(cookies, oldCookie1);86 doesIncludeCookie(cookies, oldCookie2);87 });88 it('should be able to delete one cookie', async () => {89 await driver.deleteCookie(newCookie.name);90 let cookies = await driver.allCookies();91 doesNotIncludeCookie(cookies, newCookie);92 await driver.setCookie(newCookie);93 cookies = await driver.allCookies();94 doesIncludeCookie(cookies, newCookie);95 await driver.deleteCookie(newCookie.name);96 cookies = await driver.allCookies();97 doesNotIncludeCookie(cookies, newCookie);98 doesIncludeCookie(cookies, oldCookie1);99 doesIncludeCookie(cookies, oldCookie2);100 });101 it('should be able to delete all cookies', async () => {102 await driver.deleteCookie(newCookie.name);103 let cookies = await driver.allCookies();104 doesNotIncludeCookie(cookies, newCookie);105 await driver.setCookie(newCookie);106 cookies = await driver.allCookies();107 doesIncludeCookie(cookies, newCookie);108 await driver.deleteAllCookies();109 cookies = await driver.allCookies();110 cookies.length.should.equal(0);111 doesNotIncludeCookie(cookies, oldCookie1);112 doesNotIncludeCookie(cookies, oldCookie2);113 });114 });...
safari-ssl-e2e-specs.js
Source:safari-ssl-e2e-specs.js
...75 await driver.setCookie(oldCookie1);76 await driver.deleteCookie(secureCookie.name);77 });78 it('should be able to set a secure cookie', async function () {79 let cookies = await driver.allCookies();80 doesNotIncludeCookie(cookies, secureCookie);81 await driver.setCookie(secureCookie);82 cookies = await driver.allCookies();83 doesIncludeCookie(cookies, secureCookie);84 // should not clobber old cookie85 doesIncludeCookie(cookies, oldCookie1);86 });87 it('should be able to set a secure cookie', async function () {88 await driver.setCookie(secureCookie);89 let cookies = await driver.allCookies();90 doesIncludeCookie(cookies, secureCookie);91 // should not clobber old cookie92 doesIncludeCookie(cookies, oldCookie1);93 await driver.deleteCookie(secureCookie.name);94 cookies = await driver.allCookies();95 doesNotIncludeCookie(cookies, secureCookie);96 });97 });98 });...
cookie.test.js
Source:cookie.test.js
...31 * https://macacajs.github.io/macaca-wd/#allCookies32 */33 describe('allCookies', async () => {34 it('should work', async () => {35 await driver.allCookies();36 assert.equal(server.ctx.url, '/wd/hub/session/sessionId/cookie');37 assert.equal(server.ctx.method, 'GET');38 });39 });40 /**41 * https://macacajs.github.io/macaca-wd/#deleteAllCookies42 */43 describe('deleteAllCookies', async () => {44 it('should work', async () => {45 await driver.deleteAllCookies();46 assert.equal(server.ctx.url, '/wd/hub/session/sessionId/cookie');47 assert.equal(server.ctx.method, 'DELETE');48 assert.deepEqual(server.ctx.request.body, {});49 assert.deepEqual(server.ctx.response.body, {...
TestAllCookies.spec.js
Source:TestAllCookies.spec.js
1'use strict'2const path = require('path')3const cwd = process.cwd()4const {testServer} = require('@applitools/test-server')5const {Target} = require(cwd)6const spec = require(path.resolve(cwd, 'dist/spec-driver'))7const {setupEyes} = require('@applitools/test-utils')8const adjustUrlToDocker = require('../util/adjust-url-to-docker')9describe('TestCookies', () => {10 let server, corsServer11 let driver, destroyDriver12 before(async () => {13 const staticPath = path.join(__dirname, '../fixtures/cookies')14 const corsStaticPath = path.join(__dirname, '../fixtures/cookies/cors_images')15 corsServer = await testServer({16 port: 5560,17 staticPath: corsStaticPath,18 allowCors: true,19 middlewares: ['cookies'],20 })21 server = await testServer({22 port: 5557,23 staticPath,24 middlewares: ['cookies', 'handlebars'],25 hbData: {26 imageSrc: adjustUrlToDocker('http://localhost:5560/images/cookie.jpeg'),27 },28 })29 })30 after(async () => {31 await server.close()32 await corsServer.close()33 })34 beforeEach(async () => {35 ;[driver, destroyDriver] = await spec.build({browser: 'chrome'})36 })37 afterEach(async () => {38 await destroyDriver()39 })40 it('get cookies (@all-cookies)', async () => {41 const url = adjustUrlToDocker(42 'http://localhost:5557/index.hbs?name=token&value=12345&path=/images',43 )44 await spec.visit(driver, url)45 const eyes = setupEyes({vg: true, disableBrowserFetching: true})46 await eyes.open(driver, 'AllCookies', 'TestAllCookies', {width: 800, height: 600})47 await eyes.check(Target.window())48 await eyes.close()49 })...
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3 .withCapabilities(webdriver.Capabilities.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.getAllCookies().then(function(cookies) {13 console.log(cookies);14});15driver.quit();
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3 .withCapabilities({4 })5 .build();6driver.manage().window().maximize();7driver.manage().timeouts().implicitlyWait(5000);8driver.findElement(webdriver.By.name('q')).sendKeys('Selenium');9driver.findElement(webdriver.By.name('btnK')).click();10driver.manage().timeouts().implicitlyWait(5000);11driver.findElement(webdriver.By.linkText('Selenium - Web Browser Automation')).click();12driver.manage().timeouts().implicitlyWait(5000);13driver.findElement(webdriver.By.linkText('Downloads')).click();14driver.manage().timeouts().implicitlyWait(5000);15driver.findElement(webdriver.By.linkText('Download')).click();
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var serverConfig = {4};5var desiredCaps = {6};7var driver = wd.promiseChainRemote(serverConfig);8driver.init(desiredCaps)9 .then(function () {10 return driver.allCookies();11 })12 .then(function (cookies) {13 console.log('Cookies: ' + JSON.stringify(cookies));14 })15 .fin(function () {16 return driver.quit();17 })18 .done();19var wd = require('wd');20var assert = require('assert');21var serverConfig = {22};23var desiredCaps = {24};25var driver = wd.promiseChainRemote(serverConfig);26driver.init(desiredCaps)27 .then(function () {28 return driver.deleteCookie('my_cookie');29 })30 .then(function () {31 return driver.allCookies();32 })33 .then(function (cookies) {34 console.log('Cookies: ' + JSON.stringify(cookies));35 })36 .fin(function () {37 return driver.quit();38 })39 .done();40var wd = require('wd');41var assert = require('assert');42var serverConfig = {43};44var desiredCaps = {45};46var driver = wd.promiseChainRemote(serverConfig);47driver.init(desiredCaps
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2driver.manage().addCookie('myCookie','myCookieValue');3driver.manage().getCookie('myCookie').then(function(cookie){4 console.log(cookie);5 driver.quit();6});7var webdriver = require('selenium-webdriver');8driver.manage().addCookie('myCookie','myCookieValue');9driver.manage().getCookies().then(function(cookies){10 console.log(cookies);11 driver.quit();12});13var webdriver = require('selenium-webdriver');14driver.manage().addCookie('myCookie','myCookieValue');15driver.manage().deleteCookie('myCookie');16driver.manage().getCookies().then(function(cookies){17 console.log(cookies);18 driver.quit();19});20var webdriver = require('selenium-webdriver');21driver.manage().addCookie('myCookie','myCookieValue');22driver.manage().deleteAllCookies();23driver.manage().getCookies().then(function(cookies){24 console.log(cookies);25 driver.quit();26});27var webdriver = require('selenium-webdriver');28driver.manage().addCookie('myCookie','myCookieValue');29driver.manage().deleteAllCookies();30driver.manage().getCookies().then(function
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder().forBrowser('chrome').build();3driver.manage().addCookie({name: 'foo', value: 'bar'});4driver.manage().getCookies().then(function(cookies) {5 console.log(cookies);6});7driver.quit();8var webdriver = require('selenium-webdriver');9var driver = new webdriver.Builder().forBrowser('chrome').build();10driver.manage().addCookie({name: 'foo', value: 'bar'});11driver.manage().getCookies().then(function(cookies) {12 console.log(cookies);13});14driver.quit();15var webdriver = require('selenium-webdriver');16var driver = new webdriver.Builder().forBrowser('chrome').build();17driver.manage().addCookie({name: 'foo', value: 'bar'});18driver.manage().getCookies().then(function(cookies) {19 console.log(cookies);20});21driver.quit();22var webdriver = require('selenium-webdriver');23var driver = new webdriver.Builder().forBrowser('chrome').build();24driver.manage().addCookie({name: 'foo', value: 'bar'});25driver.manage().getCookies().then(function(cookies) {26 console.log(cookies);27});28driver.quit();29var webdriver = require('selenium-webdriver');30var driver = new webdriver.Builder().forBrowser('chrome').build();31driver.manage().addCookie({name: 'foo', value: 'bar'});32driver.manage().getCookies().then(function(cookies) {33 console.log(cookies);34});35driver.quit();36var webdriver = require('selenium-webdriver');37var driver = new webdriver.Builder().forBrowser('chrome').build();38driver.manage().addCookie({name: 'foo', value: 'bar'});39driver.manage().getCookies
Using AI Code Generation
1var wd = require('wd');2var driver = wd.remote();3driver.init({4}, function() {5 driver.allCookies(function(err, cookies) {6 if (err) {7 console.log(err);8 } else {9 console.log(cookies);10 }11 });12 });13});
Using AI Code Generation
1var webdriver = require('wd');2var assert = require('assert');3var fs = require('fs');4var path = require('path');5var desired = {6 chromeOptions: {7 }8};9var driver = webdriver.remote("ondemand.saucelabs.com", 80, "USERNAME", "KEY");10driver.on('status', function(info) {11 console.log(info.cyan);12});13driver.on('command', function(meth, path, data) {14 console.log(' > ' + meth.yellow, path.grey, data || '');15});16driver.init(desired, function() {17 driver.allCookies(function(err, cookies) {18 if (err) {19 console.log(err);20 } else {21 console.log(cookies);22 }23 });24 });25});
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!!