Search code examples
playwrightplaywright-test

How can I use browserContext in the playwright test runner?


I'm using playwright to test a PWA (Progressive Web App) and I want to test the offline behavior.

browserContext has a setOffline method.

When calling playwright as a library, I can set browserContext like this:

// example.js
const playwright = require('playwright');

(async () => {
  const browser = await playwright.chromium.launch({
    channel: 'msedge',
  });
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://www.microsoft.com/edge');
  await context.setOffline(true);
  await page.screenshot({ path: 'example.png' });

  await browser.close();
})();

But for my PWA, I'm using the bundled playwright test runner.

I have configured my test runner to use 5 devices-- desktop Chrome, Firefox, and Webkit, as well as mobile Webkit and mobile Chrome. I want to enter and exit offline mode in all of them within the test to confirm my PWA's behavior.

How can I set browserContext in the test runner? It doesn't seem to be available within the test.


Solution

  • Never actually tried this, but as I see it, just taking the context instance into the async function should be fine:

    test('context', async({ page, context }) => {
        await page.goto('https://www.microsoft.com/edge');
        await context.setOffline(true);
        await page.screenshot({ path: 'example.png' });
    });