Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add cookies in playwright test

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();
like image 386
ugabuga77 Avatar asked Dec 05 '25 21:12

ugabuga77


1 Answers

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());
});
like image 177
Clement Poncet Avatar answered Dec 08 '25 12:12

Clement Poncet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!