How to use getNamedCookie method in Webdriverio

Best JavaScript code snippet using webdriverio-monorepo

Run Webdriverio automation tests on LambdaTest cloud grid

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

cookies.test.js

Source: cookies.test.js Github

copy
1const request = require('supertest');
2const nock = require('nock');
3
4const { default: app } = require('../../../build/app');
5const { createSession } = require('./helpers');
6
7describe('Cookies', () => {
8  let sessionId;
9
10  beforeEach(async () => {
11    nock(/plumadriver/)
12      .get(/.*/)
13      .reply(200, '<html></html>');
14
15    sessionId = await createSession(request, app);
16  });
17
18  const addCookie = async (cookie, expectedStatusCode = 200) => {
19    const {
20      body: { value },
21    } = await request(app)
22      .post(`/session/${sessionId}/cookie`)
23      .send({ cookie })
24      .expect(expectedStatusCode);
25    return value;
26  };
27
28  const getNamedCookie = async (name, expectedStatusCode = 200) => {
29    const {
30      body: { value },
31    } = await request(app)
32      .get(`/session/${sessionId}/cookie/${name}`)
33      .expect(expectedStatusCode);
34    return value;
35  };
36
37  it('adds a valid cookie', async () => {
38    await request(app)
39      .post(`/session/${sessionId}/url`)
40      .send({
41        url: 'http://plumadriver.com',
42      });
43
44    const requestCookie = {
45      secure: false,
46      httpOnly: false,
47      expiry: 3654907200,
48      domain: 'plumadriver.com',
49      name: 'valid',
50      path: '/',
51      value: 'isValid',
52    };
53
54    await addCookie(requestCookie);
55    expect(await getNamedCookie(requestCookie.name)).toMatchObject({
56      name: requestCookie.name,
57      value: requestCookie.value,
58      domain: requestCookie.domain,
59      path: requestCookie.path,
60    });
61  });
62
63  it('handles dot prefix in cookie domains', async () => {
64    await request(app)
65      .post(`/session/${sessionId}/url`)
66      .send({
67        url: 'http://plumadriver.com/',
68      });
69
70    const requestCookie = {
71      secure: true,
72      httpOnly: true,
73      expiry: 1573253325754,
74      domain: '.plumadriver.com',
75      name: 'foo',
76      path: '/',
77      value: 'bar',
78    };
79
80    await addCookie(requestCookie);
81    expect(await getNamedCookie(requestCookie.name)).toMatchObject({
82      name: requestCookie.name,
83      value: requestCookie.value,
84      domain: 'plumadriver.com',
85    });
86  });
87
88  it('adds a cookie filling in missing optional fields', async () => {
89    await request(app)
90      .post(`/session/${sessionId}/url`)
91      .send({
92        url: 'http://plumadriver.com/',
93      });
94
95    const requestCookie = {
96      name: 'foo',
97      value: 'bar',
98    };
99
100    await addCookie(requestCookie);
101    expect(await getNamedCookie(requestCookie.name)).toMatchObject({
102      name: requestCookie.name,
103      value: requestCookie.value,
104      domain: 'plumadriver.com',
105      path: '/',
106    });
107  });
108
109  it.each([
110    { value: 'foo' },
111    {
112      name: 'foo',
113      value: 'bar',
114      expiry: -1,
115    },
116    {
117      name: 'foo',
118      value: 'bar',
119      httpOnly: 'true',
120    },
121    {
122      name: 'foo',
123      value: 'bar',
124      secure: 'false',
125    },
126  ])('throws InvalidArgument error on invalid fields', async cookie => {
127    await request(app)
128      .post(`/session/${sessionId}/url`)
129      .send({
130        url: 'http://plumadriver.com/',
131      })
132      .expect(200);
133
134    const { error } = await addCookie(cookie, 400);
135    expect(error).toBe('invalid argument');
136  });
137
138  it('handles .local top-level domains', async () => {
139    nock(/foo/)
140      .defaultReplyHeaders({
141        'Set-Cookie': 'replyCookie=replyValue; Path=/',
142      })
143      .get('/')
144      .reply(200, '<html></html>');
145
146    await request(app)
147      .post(`/session/${sessionId}/url`)
148      .send({
149        url: 'http://bar.foo.local',
150      })
151      .expect(200);
152
153    await addCookie({ name: 'requestCookie', value: 'requestValue' });
154
155    expect(await getNamedCookie('requestCookie')).toMatchObject({
156      name: 'requestCookie',
157      value: 'requestValue',
158      domain: 'bar.foo.local',
159    });
160
161    expect(await getNamedCookie('replyCookie')).toMatchObject({
162      name: 'replyCookie',
163      value: 'replyValue',
164      domain: 'bar.foo.local',
165    });
166  });
167
168  it('respects matching cookie paths', async () => {
169    await request(app)
170      .post(`/session/${sessionId}/url`)
171      .send({
172        url: 'http://plumadriver.com/a/b',
173      })
174      .expect(200);
175
176    const requestCookie = {
177      name: 'someName',
178      value: 'someValue',
179      path: '/a',
180      domain: '.plumadriver.com',
181    };
182
183    await addCookie(requestCookie);
184
185    expect(await getNamedCookie(requestCookie.name)).toMatchObject({
186      name: requestCookie.name,
187      value: requestCookie.value,
188      domain: 'plumadriver.com',
189      path: requestCookie.path,
190    });
191  });
192
193  it('throws NoSuchCookie on mismatched path', async () => {
194    await request(app)
195      .post(`/session/${sessionId}/url`)
196      .send({
197        url: 'http://plumadriver.com/',
198      })
199      .expect(200);
200
201    const requestCookie = {
202      name: 'noCookie',
203      value: 'noValue',
204      domain: 'plumadriver.com',
205      path: '/baz',
206    };
207
208    await addCookie(requestCookie);
209    const { error } = await getNamedCookie(requestCookie.name, 404);
210    expect(error).toBe('no such cookie');
211  });
212
213  it('deletes an existing cookie by name', async () => {
214    await request(app)
215      .post(`/session/${sessionId}/url`)
216      .send({
217        url: 'http://plumadriver.com/',
218      })
219      .expect(200);
220
221    const requestCookie = {
222      name: 'delete',
223      value: 'true',
224    };
225
226    await addCookie(requestCookie);
227
228    await request(app)
229      .delete(`/session/${sessionId}/cookie/${requestCookie.name}`)
230      .expect(200);
231
232    const { error } = await getNamedCookie(requestCookie.name, 404);
233    expect(error).toBe('no such cookie');
234  });
235
236  it('deletes all associated cookies', async () => {
237    await request(app)
238      .post(`/session/${sessionId}/url`)
239      .send({
240        url: 'http://plumadriver.com/',
241      })
242      .expect(200);
243
244    await addCookie({
245      name: 'notAssociated',
246      value: 'true',
247      domain: '.pluma.com',
248      path: '/',
249    });
250
251    await addCookie({
252      name: 'alsoNotAssociated',
253      value: 'true',
254      domain: '.plumadriver.com',
255      path: '/plumadriver',
256    });
257
258    await addCookie({
259      name: 'associated',
260      value: 'true',
261      domain: '.plumadriver.com',
262      path: '/',
263    });
264
265    await addCookie({
266      name: 'alsoAssociated',
267      value: 'true',
268      domain: '.plumadriver.com',
269    });
270
271    // delete all cookies
272    await request(app)
273      .delete(`/session/${sessionId}/cookie`)
274      .expect(200);
275
276    // get all cookies
277    expect((await getNamedCookie('')).map(({ name }) => name)).toStrictEqual(
278      [],
279    );
280  });
281
282  it('gets all associated cookies', async () => {
283    await addCookie({
284      name: 'notAssociated',
285      value: 'true',
286      domain: '.anotherwebsite.com',
287      path: '/',
288    });
289
290    await request(app)
291      .post(`/session/${sessionId}/url`)
292      .send({
293        url: 'http://plumadriver.com/',
294      })
295      .expect(200);
296
297    const plumadriverCookie = {
298      name: 'associated',
299      value: 'true',
300      domain: 'plumadriver.com',
301      path: '/',
302    };
303
304    await addCookie(plumadriverCookie);
305
306    const {
307      body: { value: cookies },
308    } = await request(app).get(`/session/${sessionId}/cookie`);
309
310    expect(cookies).toStrictEqual([plumadriverCookie]);
311  });
312});
313
Full Screen

cookie.js

Source: cookie.js Github

copy
1'use strict';
2
3function *getAllCookies(next) {
4  this.state.value = yield this.device.getAllCookies();
5  yield next;
6}
7
8function *getNamedCookie(next) {
9  const body = this.request.body;
10  const name = body.name;
11
12  this.state.value = yield this.device.getNamedCookie(name);
13  yield next;
14}
15
16function *addCookie(next) {
17  const body = this.request.body;
18  const cookie = body.cookie;
19  this.state.value = yield this.device.addCookie(cookie);
20  yield next;
21}
22
23function *deleteCookie(next) {
24  const body = this.request.body;
25  const name = body.name;
26
27  this.state.value = yield this.device.deleteCookie(name);
28  yield next;
29}
30
31function *deleteAllCookies(next) {
32  this.state.value = yield this.device.deleteAllCookies();
33  yield next;
34}
35
36module.exports = {
37  getAllCookies,
38  getNamedCookie,
39  addCookie,
40  deleteCookie,
41  deleteAllCookies
42};
43
Full Screen

getNamedCookie.js

Source: getNamedCookie.js Github

copy
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3/**
4 * The Get Named Cookie command returns the cookie with the requested name from the
5 * associated cookies in the cookie store of the current browsing context's active document.
6 * If no cookie is found, a no such cookie error is returned.
7 *
8 * @alias browser.getNamedCookie
9 * @see https://w3c.github.io/webdriver/#dfn-get-named-cookie
10 * @param {string} name  name of the cookie to retrieve
11 * @return {object}      A serialized cookie, with name and value fields. There are a number of optional fields like `path`, `domain`, and `expiry-time` which may also be present.
12 */
13async function getNamedCookie({ name }) {
14    const page = this.getPageHandle();
15    const cookies = await page.cookies();
16    const cookie = cookies.find((cookie) => cookie.name === name);
17    if (!cookie) {
18        throw new Error(`No cookie with name ${name}`);
19    }
20    return cookie;
21}
22exports.default = getNamedCookie;
23
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Webdriverio on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)