Add cookies in playwright test

42k views Asked by At

No matter what I do I get an error (either X.cookies is not a function or X.addCookies is not a function). I tried with context, page.context. browserContext etc. and it always ends up in the same way (ok, page.context as well as browserContext are undefined so error is different).

Context:

  • Playwright Version: 1.4.2
  • Operating System: Ubuntu 20.4
  • Node.js version: 10.15.1
  • Browser: Chromium

Code:

beforeEach(async function fn() {
this.timeout(20000);
browser = await chromium.launch({ headless: false });

const context = await browser.newContext();
page = await context.newPage();

await page
  .goto("http://localhost:4200/#/login", {
    waitUntil: "networkidle0",
  })
  .catch(() => {});

});

and in test:

      // await context.addCookies([
  //   { name: "csrftoken", value: cookieToken, path: "/" },
  //   { name: "sessionid", value: cookieSession, path: "/" },
  // ]);
  // await context.cookies();
7

There are 7 answers

0
keshav On BEST ANSWER

right after you have your context, you should be able to use it as an example below: await context.addCookies([{name:"csrftoken", value: "mytokenvalue123", url: "your.application.url"}]);

0
Abdul Kalam On

we can use the current working page context to add the cookies.

 const browserContext = page.context();

    // Add cookies to the browserContext
    browserContext.addCookies([
      {
        name: 'next-auth.session-token',
        value: 'FAKE_TOKEN',
        domain: 'localhost',
        path: '/',
        expires: -1,
        httpOnly: true,
        secure: false,
        sameSite: 'Lax',
      },
    ]);
0
Vivian On

I had some struggle, so I ended to use this:

  await page.addInitScript((cookie: string) => {
    document.cookie = cookie;
  }, cookie);

Reference: https://playwright.dev/docs/api/class-page#page-add-init-script

1
Clement Poncet On

I had to use context directly instead of browser context, otherwise some data would not load correctly (specifically in a SvelteKit app):

test('index page has expected content when logged in', async ({ page, context }) => {
    await context.addCookies([
        { name: 'sessionid', value: 'random', path: '/', domain: 'localhost' }
    ]);

    await page.goto('/');
    expect(await page.textContent('h1')).toBe('My title');
    console.log(await context.cookies());
});
1
SoonerLR On

Setting cookies is pretty straightforward. You can to take advantage of the browser fixture.

test("Go Test An Application", async ({ page, browser }) => {

    // Using the browser fixture, you can get access to the BrowserContext
    const browserContext = await browser.newContext();

    // Add cookies to the browserContext
    const cookieVals = await setCookieVals();
    browserContext.addCookies(cookieVals)

    // First we will go to the Applicaiton URL
    const appURL = "https://stackoverflow.com/"
    page.goto(`${appURL}`);

    await page.waitForTimeout(3000);

});

export async function setCookieVals() {

    const cookies = [
        {name:"cookie1", value:"349", path:"/", domain:"stackoverflow"},
        {name:"cookie2", value:"1", path:"/", domain:"stackoverflow"},
        {name:"cookie3", value:"4000", path:"/", domain:"stackoverflow"},
    ]

    return cookies;
}
0
nrako On

In order to set cookies with playwright, you would need to add both path & domain or url. Cf. the commented code in addCookies docs

**browserContext.addCookies(cookies)**

cookies <Array<Object>>
name <string>
value <string>
url <string> either url or domain / path are required. Optional. // ***** NOTE *****
domain <string> either url or domain / path are required Optional. // ***** NOTE *****
path <string> either url or domain / path are required Optional. // ***** NOTE *****
expires <number> Unix time in seconds. Optional.
httpOnly <boolean> Optional.
secure <boolean> Optional.
sameSite <"Strict"|"Lax"|"None"> Optional.

returns: <Promise<void>>

This is different behavior than standard behavior where domain is optional.

1
Peter S On

const context is set only inside the beforeEach method and it's not avilable in your test.

Define it as a global variable