Add cookies in playwright test

Viewed 11467

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();
4 Answers

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

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"}]);

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.

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

Define it as a global variable

Related