How to use driver.allCookies method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

mobile_driver.js

Source:mobile_driver.js Github

copy

Full Screen

...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}`;...

Full Screen

Full Screen

safari-basic-e2e-specs.js

Source:safari-basic-e2e-specs.js Github

copy

Full Screen

...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 () {...

Full Screen

Full Screen

Appium JS commands.js

Source:Appium JS commands.js Github

copy

Full Screen

...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...

Full Screen

Full Screen

cookies-base.js

Source:cookies-base.js Github

copy

Full Screen

...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      });...

Full Screen

Full Screen

safari-cookie-e2e-specs.js

Source:safari-cookie-e2e-specs.js Github

copy

Full Screen

...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  });...

Full Screen

Full Screen

safari-ssl-e2e-specs.js

Source:safari-ssl-e2e-specs.js Github

copy

Full Screen

...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  });...

Full Screen

Full Screen

cookie.test.js

Source:cookie.test.js Github

copy

Full Screen

...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, {...

Full Screen

Full Screen

TestAllCookies.spec.js

Source:TestAllCookies.spec.js Github

copy

Full Screen

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  })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4const assert = chai.assert;5const should = chai.should();6const expect = chai.expect;7chai.use(chaiAsPromised);8const serverConfig = {9};10const driverConfig = {11};12const driver = wd.promiseChainRemote(serverConfig);13describe('Test suite', function() {14  this.timeout(300000);15  before(function() {16    return driver.init(driverConfig);17  });18  after(function() {19    return driver.quit();20  });21  it('test', function() {22    return driver.allCookies();23  });24});25{26  "scripts": {27  },28  "dependencies": {29  }30}31Error: An unknown server-side error occurred while processing the command. Original error: Error Domain=XCTDaemonErrorDomain Code=1 "The request to launch "com.apple.calculator" failed." UserInfo={NSLocalizedDescription=The request to launch "com.apple.calculator" failed., NSUnderlyingError=0x7f8d4f1e4b20 {Error Domain=XCTDaemonErrorDomain Code=1 "Launch error: Error Domain=com.apple.dt.xctest.error Code=1 \"The application “Calculator” could not be launched because the application process exited unexpectedly. If you believe this error represents a bug, please attach the log file at /Users/username/Library/Developer/Xcode/DerivedData/WebDriverAgent-brdadhpuduowllgivnnv

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require('webdriverio');2const assert = require('assert');3const opts = {4  capabilities: {5  }6};7async function main() {8  const client = await wdio.remote(opts);9  const cookies = await client.allCookies();10  console.log(cookies);11  await client.deleteSession();12  return cookies;13}14main();15const wdio = require('webdriverio');16const assert = require('assert');17const opts = {18  capabilities: {19  }20};21async function main() {22  const client = await wdio.remote(opts);23  const cookies = await client.allCookies();24  console.log(cookies);25  await client.deleteSession();26  return cookies;27}28main();29const wdio = require('webdriverio');30const assert = require('

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require('webdriverio');2const assert = require('assert');3const opts = {4    capabilities: {5    }6};7async function main() {8    const client = await wdio.remote(opts);9    const cookies = await client.allCookies();10    console.log(cookies);11    assert(cookies.length > 0);12    await client.deleteSession();13}14main();15[0-0] 2020-02-21T09:04:37.958Z INFO webdriver: DATA { capabilities:16[0-0]    { alwaysMatch:17[0-0]       { platformName: 'iOS',18[0-0]         app: 'safari' },19[0-0]      firstMatch: [ {} ] },20[0-0]    { platformName: 'iOS',21[0-0]      app: 'safari' } }

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require('webdriverio');2const assert = require('assert');3const opts = {4  desiredCapabilities: {5  },6};7(async function example() {8  const client = await wdio.remote(opts);9  const cookies = await client.allCookies();10  console.log(cookies);11  await client.deleteSession();12})();13[ { name: 's_fid',14    sameSite: 'None' },15  { name: 's_nr',16    sameSite: 'None' },17  { name: 's_ppv',18    sameSite: 'None' },19  { name: 's_ppvl',20    sameSite: 'None' },21  { name: 's_cc',22    sameSite: 'None' },23  { name: 's_sq',

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriverio = require('webdriverio');2var options = {3  desiredCapabilities: {4  }5};6var client = webdriverio.remote(options);7client.init()8  .then(() => client.allCookies())9  .then((cookies) => {10    console.log('Cookies: ' + JSON.stringify(cookies));11  })12  .catch((err) => console.log(err))13  .end();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3    .forBrowser('selenium')4    .build();5driver.manage().getCookies().then(function(cookies) {6    console.log(cookies);7});8driver.quit();

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 Xcuitest Driver automation tests on LambdaTest cloud grid

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

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful