Scope, auto and setup/teardown
A fixture's scope defines how long it lives: test (the default) creates it for every test, worker once per worker process. A worker fixture cannot depend on test fixtures, as it lives longer, and after a test fails the worker restarts and the fixture is created again. Auto fixtures run unrequested per test or per worker, by scope, for cross-cutting concerns, and workerIndex gives unique data per worker.
Patterns · Fixtures
A service token is fetched anew in 300 tests. How to get it once per worker and what happens when a test fails?
Each of 300 tests requests a service token before starting: 300 extra calls and seconds on each. The token does not change between tests, so it can be taken once. But an account that a test modifies cannot be shared. A fixture scope decides exactly this: what the fixture covers and how long it lives. This lesson covers the test and worker scopes, auto fixtures and the teardown order, and situations where fixtures do not work as you expect.
How it works and why. The test scope is the default: a new fixture is created and torn down for every test. The worker scope creates the fixture once per worker process and it lives as long as the worker. The runner starts several workers in parallel and each has its own instance of a worker fixture, so this is not "one for the whole run" but "one per worker". That is a reasonable price: an expensive resource is created a few times, not hundreds, and workers do not share state.
The main rule follows: a worker fixture cannot depend on a test fixture (page, or request in test scope), because it lives longer, and when you try, the runner reports an error. The reverse is fine: a test fixture can easily use a worker fixture. One more nuance: when a test fails, Playwright discards the worker process and starts a new one for the remaining tests, so as not to carry dirty state. For a worker fixture this means creating it again: the token is fetched anew.
How long each fixture lives
Which scope to choose
New for each test
Everything the test changes: an account, a page, data. Isolation matters more than speed.
One per worker
Expensive and immutable resources: a token, a database connection, an unchanging reference.
Example: a token per worker, an account per test. Four important places are marked.
type WorkerFx = { apiToken: string };
type TestFx = { account: Account };
1export const test = base.extend<TestFx, WorkerFx>({
apiToken: [
2 async ({}, use) => {
const token = await fetchServiceToken();
await use(token);
},
3 { scope: 'worker' },
],
4 account: async ({ request, apiToken }, use) => {
const acc = await createAccount(request, apiToken);
await use(acc);
await deleteAccount(request, apiToken, acc.id);
},
});
- The second type parameter is worker fixtures: this is how TypeScript tells them from test fixtures.
- The first argument is an empty pattern
{}: a worker fixture cannot request test fixtures. - The pair
[function, { scope: 'worker' }]: without options the fixture would have test scope. - A test fixture uses a worker fixture: a direct dependency is allowed in this direction.
The token is requested once per worker, while the account is created and deleted around every test. Teardown runs in reverse: the account is deleted first, and only then is the token needed for the deletion released. Because of this order deleteAccount always has a valid token.
Auto fixtures. The option { auto: true } starts a fixture for every test even if the test did not request it. It fits cross-cutting things: collecting uncaught page errors (pageerror), logging, screenshots on failure.
pageErrors: [
async ({ page }, use) => {
const errors: string[] = [];
page.on('pageerror', (e) => errors.push(e.message));
await use();
// runs after every test even without a request
expect(errors).toEqual([]);
},
{ auto: true },
],
Here the fixture subscribes to events itself and after the test checks that there were no errors. An error in a fixture's teardown also turns the test red. But such magic is hidden: a new colleague will not see in the test why it fails. So keep auto for genuinely cross-cutting things and document them in code.
Unique data per worker. A shared worker fixture for data created in the system must give unique values, because workers run simultaneously. For this the third parameter, workerInfo, is passed in.
testUser: [
async ({}, use, workerInfo) => {
// a unique name per worker: no conflicts in a parallel run
const user = await createUser('qa-w' + workerInfo.workerIndex);
await use(user);
await deleteUser(user.id);
},
{ scope: 'worker' },
],
workerIndex is unique for every worker process started, so two workers will not create "qa-w0" at the same time. After a worker restart the index changes, so names do not repeat. What it does not guarantee is that the user is clean. If tests change the user (a balance, settings), worker scope is wrong for it.
Limits and alternatives. A worker fixture saves time only when the resource is really expensive and immutable and there are many tests per worker. If tests change the data, the benefit turns into abuse: tests begin to depend on order. For one-off setup across the whole run (say, bringing up a database) use globalSetup or a setup project, because a worker fixture runs in every worker. Teardown does not guarantee that code runs if the process is killed by an external signal, so a separate mechanism to remove stale data in the test environment is useful. Fixtures can also be limited in time through the timeout option if creating a resource may hang.
Common mistakes.
- A worker fixture depends on
pageor another test fixture: the runner does not allow it because the resource outlives its dependency. - A mutable resource in worker scope (an account, a balance): tests on one worker affect each other and depend on order.
- A fixed name in a worker fixture (
'qa-user'): two workers create the same user and conflict. - Many auto fixtures with complex logic: the test slows down and fails for reasons not visible in its code.
- Cleanup in a worker fixture that depends on state a test could have changed: the cleanup fails and disturbs others.
Check yourself
The worker fixture apiToken is declared with async ({ page }, use) and { scope: 'worker' }. What happens?
Answer
The runner reports a scope error: a worker fixture cannot depend on the test fixture page because it lives longer. Either get the resource without page (for example, a separate APIRequestContext in the worker) or make the fixture test-scoped.
A test with the worker fixture testUser failed, the worker was restarted, and the following tests also request testUser. How many times will the setup of testUser run and why?
Answer
At least twice: once in the original worker and again in the new one that Playwright starts after the failure so as not to carry dirty state over. So creating the user must be safe to repeat and the name unique through workerIndex.