Skip to content

Test Automation

Playwright Fixtures Explained: Setup, Scope and Reuse

JL Jeremy Luong · Author
12 min read
Playwright fixtures explained: setup, scope, and reuse without hidden state (cover image)

Playwright fixtures are the part of a suite people copy before they understand. A fixture does two jobs at once: it builds what a test needs, and it tears that down when the test finishes. Done well, setup lives in one place and every test asks for it by name. Done badly, the fixture becomes a shared object that couples tests in ways nobody can see from the test file.

This post covers the first job of Playwright fixtures: setup and reuse. What a fixture is, the two scopes Playwright provides, how use and tear down ordering work, and the shapes I’d flag as hidden state when auditing a suite. Test data is a separate problem with its own failure modes, and it gets its own post.

What Playwright fixtures actually are

A fixture is a named value the runner prepares before your test and disposes of afterward (the Playwright fixtures documentation covers the full API). You ask for one by naming it in the test’s argument object:

// Assuming baseURL is set in playwright.config.ts
test('shows the account heading', async ({ page }) => {
  await page.goto('/account');
  await expect(page.getByRole('heading', { level: 1 })).toHaveText('Account');
});

That page argument isn’t a convenience parameter. It’s a request. Playwright builds the page, hands it over for the length of the test, then closes it along with the browser context it lives in. The same mechanism handles anything you register yourself.

Compare that with hooks. A beforeEach that signs in and resets a setting needs a matching afterEach somewhere else in the file. That half often gets written later, by someone with a different idea of what “reset” means. A fixture keeps both halves together, so setup is something you can read, change or delete in one place. Fixtures are also lazy: three of twenty tests needing a stubbed geolocation means the other seventeen never pay for it.

Built-in Playwright fixtures and the scope each one uses

These are the built-ins you’ll reach for most. Their scopes explain most of the surprising behavior around them.

FixtureWhat it gives youScope
pageA fresh page in its own browser contexttest
contextThe browser context that page belongs totest
requestAn APIRequestContext for HTTP callstest
browserNameThe current browser: chromium, firefox or webkitworker
browserThe shared browser instanceworker

browserName is a worker-scoped option rather than a plain value. It carries whatever the project config selected for the run, and you can override it the same way as any other option. The split that matters most is between those two scopes. The page and its context are rebuilt for every test, while the browser process is shared by every test in the same worker. Two tests never see each other’s cookies, even though they share one browser.

Scope: test or worker, and nothing in between

Playwright fixtures come in exactly two scopes. test is the default: built before the test that asks for it, torn down after. worker is built once per worker process and lives until that process exits. There’s no file scope and no suite scope, which surprises people coming from Jest or pytest.

Diagram of Playwright fixtures scopes: one worker process holds a shared browser built once at worker scope, while tests A, B and C each get their own context and page built and torn down at test scope
One browser per worker, a fresh context and page for every test.

That gap is worth knowing about. A worker normally runs several test files in sequence, so worker scope is broader than file scope, not narrower. If you need something shared by one file only, use test.beforeAll and test.afterAll inside the file. The other option is to accept worker scope and make the value safe to share.

Worker scope needs the tuple form: worker fixtures go in the second type parameter of base.extend, and each value is wrapped as [function, { scope: 'worker' }]. Leave the options object off and you’ve written a test-scoped fixture that runs far more often than you intended.

// fixtures.ts
import { test as base } from '@playwright/test';
import { createServer } from 'node:http';

type WorkerFixtures = { stubServer: { origin: string } };

export const test = base.extend<{}, WorkerFixtures>({
  stubServer: [async ({}, use) => {
    const server = createServer((_req, res) => {
      res.writeHead(200, { 'content-type': 'text/html' });
      res.end('<h1>Stub page</h1>');
    });
    await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
    const { port } = server.address() as { port: number };

    await use({ origin: `http://127.0.0.1:${port}` });

    await new Promise<void>((resolve) => server.close(() => resolve()));
  }, { scope: 'worker' }],
});

The port comes from the operating system rather than a hardcoded number, so two workers on one machine don’t collide. On a multi-core runner those workers usually run at the same time. That’s the default, not an edge case.

Worker fixtures also get their own timeout, equal to the test timeout unless you set one with { scope: 'worker', timeout: 60_000 }. That keeps a slow setup from being charged to whichever test needs it first.

The use pattern, and the order tear down runs in

Every fixture body has the same three beats: build the value, await use(value), clean up. The use call isn’t optional. On Playwright 1.64.1, a branch that returns without reaching it fails the test with use() was not called in fixture "name". The error names the fixture, so at least it points at the right place. The worse version is the branch that throws before use: whatever it was holding never gets cleaned up, because the tear down after use never runs either.

Ordering follows from dependencies, not from declaration order:

  1. A fixture that depends on another is set up after it, and torn down before it.
  2. Non-automatic fixtures are built lazily, at the moment a test or another fixture asks for them.
  3. Test-scoped fixtures are torn down after each test.
  4. Worker-scoped fixtures are torn down when the worker process exits.
Five-step sequence: the worker fixture is built, then the test fixture that depends on it, the test body runs inside await use(value), the test fixture is torn down after each test, and the worker fixture is torn down when the worker process exits
Dependencies are set up first and torn down last.

Tear-down runs in reverse order of setup, so a wrapper is gone before the resource it wrapped.

Automatic fixtures are the exception to laziness. Add { auto: true } and the fixture runs for every test in scope, whether the test lists it or not. It is the supported way to install something globally without copying a beforeEach into every file. Be stingy with it, because every test pays the cost.

// Fail any test whose page logs a console error
// (one entry inside base.extend({ ... }))
consoleGuard: [async ({ page }, use) => {
  const errors: string[] = [];
  page.on('console', (msg) => {
    if (msg.type() === 'error') errors.push(msg.text());
  });

  await use();

  expect(errors, 'unexpected console errors').toEqual([]);
}, { auto: true }],

That one earns its place in most suites: it turns a console error nobody read into a failing test, and all it costs is a listener. The assertion sits after await use(), so it runs once the test finishes.

Composing Playwright fixtures and overriding the built-ins

Fixtures can depend on other fixtures, and that’s where reuse starts to pay. A page-object fixture asks for page, a checker asks for the page object, and a test asks for the checker. The chain is built in dependency order and unwound in reverse.

Chain of fixtures from the built-in page to a page object to a checker to the test, set up from left to right and torn down from right to left
Each fixture asks for the one before it. Tear-down unwinds the chain in reverse.

Overriding runs through the same mechanism. Asking for page inside a page override gives you the inherited value, so you can wrap it:

export const test = base.extend({
  page: async ({ page, baseURL }, use) => {
    await page.goto(baseURL!);
    await use(page);
  },
});

That’s the common case: navigate once in the fixture instead of in every test. It’s also the one to think twice about. A page override that lands on the home page quietly gives every test a starting URL, including the test that needed to start somewhere else. A goto where it’s needed stays honest, even if it’s a line longer.

Options can be overridden the same way, and replacing storageState in an override is the supported route to signing in once and reusing that session instead of driving the login form every test. When fixtures come from several modules, mergeTests combines them into one test object, which beats an .extend chain nobody can follow by the third file.

When a fixture is the wrong tool

Playwright fixtures are cheap to write and easy to overuse. These are the shapes I’d question in review.

Module-level state wearing a fixture’s name

A variable declared at module scope and assigned inside a fixture looks like a fixture and behaves like a global. If two tests in the same file read it, they’re coupled through the file, and that coupling is invisible from either test’s signature.

Parallel mode makes this worse in a way that’s easy to misread. Each worker is its own process with its own copy of the module. The variable stops being shared across the whole file and starts being shared by whichever tests land in the same worker.

That grouping changes between runs, so a test’s starting value changes with it. Nothing fails outright; the suite just gets inconsistent in a way that tracks scheduling, which is a flaky test with a cause several layers from its symptom.

Scope broader than the reason for it

Worker scope is a performance lever, and it usually gets pulled for the wrong reason. The question isn’t “can this be shared?” but “is it safe to share with every test that lands in this worker?”

A browser instance is. A signed-in account with mutable settings is not, unless no test ever changes them, and the first test that does leaves the mess for the next one. Stay at test scope until the rebuild cost is measurably painful and the shared value is read-only from the tests’ side.

A worker fixture reaching for a test fixture

Playwright refuses this outright. A worker-scoped fixture can’t depend on page, context, request or any other test-scoped fixture, and the run stops with an error naming the pair. A value built once per process can’t be built from something rebuilt per test.

The fix is to split the fixture rather than force it. Build the expensive object at worker scope from worker-scoped primitives: playwright.request.newContext() instead of request, and browser.newContext() instead of the test’s context. Then adapt it per test in a second, test-scoped fixture. Two small fixtures beat one that pretends the scopes are the same.

A fixture that hides what the test depends on

A subtler failure is a fixture that does too much without saying so. A checkoutPage fixture that signs in, adds an item, applies a coupon and lands on the payment step makes its test read like one assertion about a total. It’s really four undocumented steps, and when it breaks, the trace starts several actions after the cause. Keep the fixture to what its name promises and let the test compose the rest.

A tear down that only works on the happy path

Cleanup after await use() runs whether the test passed or failed, so it has to tolerate both. A tear down that assumes the object was fully built, or gives up at the first error, leaves the next test holding the wreckage. Make it idempotent and await it. A fixture that can’t be torn down twice isn’t finished.

Playwright fixtures and parallel workers

Playwright gets parallelism from worker processes, not threads. Each worker is its own process with its own browser. By default test files are spread across workers, while tests inside one file run in order. If those tests don’t depend on each other, the file can opt into parallel mode:

test.describe.configure({ mode: 'parallel' });

// Or for every file in a project, in playwright.config.ts
export default defineConfig({ fullyParallel: true });

Test-scoped fixtures are already parallel-safe: they’re rebuilt per test, and the page they hand you belongs to a context no other test can see. Worker-scoped fixtures are where parallel bugs live, because there’s one copy per worker shared by every test in it.

Two IDs matter here. workerInfo.workerIndex is unique for the life of the run and keeps climbing when a worker restarts. workerInfo.parallelIndex stays between 0 and workers - 1 and is stable for a slot. Use it when a fixture binds to something external: a port, a temp directory, a place in a fixed pool. Key a long-lived resource by workerIndex and you allocate a new one every time a worker restarts after a failure.

Two worker slots: slot 0 has parallelIndex 0 and its worker with workerIndex 0 is replaced after a test fails by a new worker with workerIndex 2, while slot 1 keeps parallelIndex 1 and workerIndex 1
After a failure the slot keeps its parallelIndex, but the new worker gets a new workerIndex.

Workers are also shut down after a test failure, to guarantee a clean environment for what follows. That means worker-scoped tear down runs more often on a bad day than a good one.

A Playwright fixtures checklist before you extend the base test

None of this fixes a test at the wrong layer. No fixture makes a UI test the right way to check a JSON contract; that’s a coverage question, covered in contract testing vs E2E testing. Once the layer is right, these are the questions I’d ask of a new fixture:

  • Do more than one test need this, and does it have a tear down? If the first answer is no, keep the setup inline.
  • Does the name describe exactly what it builds? If the name needs an “and”, split it.
  • Is the value safe to share for a whole worker, or only for a single test?
  • Does it run automatically? If so, is that worth the cost on every test in scope?
  • Does tear down run on failure, and is it safe to run twice?
  • Would a second worker running at the same time collide with this fixture? If yes, fix the resource or key it by parallelIndex.

Keep reading

Playwright fixtures remove the flakiness that comes from setup differing between runs. They don’t remove the kind that comes from tests sharing state through the app, which is an isolation problem rather than a setup one. If the failures you’re chasing turn out to be checks sitting at the wrong layer, how to decide which layer should catch a failure is the decision to make first. If you’re still choosing a runner, Playwright vs Selenium compares the two on the things that decide maintenance cost.

JL

Written by

Jeremy Luong

SDET Consultant

More about the author

Leave a Reply

Your email address will not be published.