Playwright fixtures are built-in DI: a test asks for dependencies in its arguments, and the runner creates and cleans them up. Dependencies are set up before dependents and torn down in reverse order; code after await use(value) is teardown that runs even after a failure or timeout. Fixtures are lazy but not a full DI container: implementations are swapped via options or fixture overrides in test.extend, not interfaces.
Patterns · Fixtures
A test creates three objects by hand and the cleanup sits after an expect that failed. Who cleans up?
In a five-line test the first three create LoginPage, PaymentsPage and an account through the API, and the last deletes the account. When the expect in the middle fails, the deletion does not run, and the database slowly fills with garbage. The same in ten files. Playwright fixtures hand creation and cleanup to the runner: the test only asks for what it needs. This lesson explains how that works, why fixtures can be seen as built-in DI and where the analogy ends.
How it works and why. Dependency Injection means an object does not create its dependencies itself but receives them from outside. In Playwright Test a test declares the fixtures it needs by destructuring the first argument: async ({ loginPage, account }) => …. The runner reads the names from this pattern (so the first argument must be an object pattern, not a variable), builds a dependency graph and calls each fixture. A fixture is a function with two parts separated by the call await use(value): the code before it is setup and the code after it is teardown. Anything the test did not request is not created: fixtures are lazy.
The order is always the same: dependencies are created before their dependants and torn down in reverse. So loginPage, which depends on page, never receives an already closed page. Teardown runs even when the test failed or timed out, and this is what removes the "cleanup after expect" problem.
The life of a fixture in one test
Figure 1. Creation goes from dependencies to dependants, teardown the other way round. The test body is in the middle.
Who is responsible for creation and cleanup
Wrong
The test does everything by hand
new, API calls and cleanup are duplicated in every file. The expect failed, so the deletion did not happen.
Right
The test asks for a fixture
Creation and deletion are described once. The test contains only the scenario, and teardown always runs.
Figure 2. A fixture moves the life cycle from the test to the runner.
Example: from manual code to fixtures. The starting point. Everything that is not the scenario sits in the test.
test('archived payment is visible', async ({ page, request }) => {
const loginPage = newLoginPage(page);
const paymentsPage = newPaymentsPage(page);
const account = awaitcreateAccountViaApi(request);
await loginPage.goto();
await loginPage.login(account.email, account.password);
awaitexpect(paymentsPage.archived.rowByText('INV-1')).toBeVisible();
// will not run if the expect above threwawaitdeleteAccountViaApi(request, account.id);
});
There are two problems. First: the lines with new and API calls repeat in every test. Second: deleting the account after expect will not run if the check fails. You can wrap everything in try/finally, but that is even more noise in every test. Now the same as fixtures. Four important places are marked.
import { test as base } from'@playwright/test';
typePages = { loginPage: LoginPage; paymentsPage: PaymentsPage };
typeData = { account: Account };
1exportconst test = base.extend<Pages & Data>({
2 loginPage: async ({ page }, use) => {
awaituse(newLoginPage(page));
},
paymentsPage: async ({ page }, use) => {
awaituse(newPaymentsPage(page));
},
account: async ({ request }, use) => {
const account = awaitcreateAccountViaApi(request);
3awaituse(account);
// runs after a failed test as well4awaitdeleteAccountViaApi(request, account.id);
},
});
export { expect } from'@playwright/test';
base.extend with a type: TypeScript knows which fixtures exist and what they return.
The fixture depends on page, so the runner creates it after page.
use passes the value to the test and suspends the fixture until the test ends.
The code after use is teardown: the account is always deleted.
There is neither new nor cleanup in the test. Exporting expect from the same file is convenient so specs have a single import. If fixtures live in several modules (pages separately, data separately), mergeTests combines them:
import { mergeTests } from'@playwright/test';
import { test as pages } from'./pages-fixtures';
import { test as data } from'./data-fixtures';
exportconst test = mergeTests(pages, data);
Limits and alternatives. The DI analogy is incomplete. In Spring or Angular the container works with interfaces and configuration, while here dependencies are names in test.extend, and an implementation can be replaced only through a fixture option (test.use) or an override in another extend. A fixture need not be complex: for two lines in one file beforeEach is enough. Scopes (test, worker), auto fixtures and options are covered in the lesson “Scope, auto and setup/teardown” and in the Playwright course (“Fixtures and scopes”). Do not turn a fixture into a scenario with ten steps: it prepares the environment, and the scenario must be visible in the test.
Common mistakes.
Forgot await use(…) or called it not in all branches: the test gets no value and the cleanup does not happen. use is called exactly once.
Named your fixture like a built-in one (page, context): it silently overrides the built-in and every test gets changed behaviour.
Cleanup is written in the test itself after expect: if the check fails, it does not run. That place for teardown belongs to a fixture.
The first argument of a fixture or test is not a pattern (async (fixtures, use)): the runner cannot see the names and throws an error.
A fixture runs a business assertion or a long scenario: the test stops showing what it does.
Check yourself
The account fixture creates an account through the API before await use(account) and deletes it after. The test failed on expect. Will the account be deleted?
Answer
Yes. The code after use runs as teardown regardless of the test result (failure, timeout). That is why cleanup belongs in a fixture rather than at the end of a test, where it would not run after an expect error.
A test requests only loginPage, while test.extend also declares paymentsPage and account. Will they be created?
Answer
No. Fixtures are lazy: the runner creates only those the test requested, plus their dependencies. Without a request, paymentsPage and account are not created and their teardown does not run either. The exception is auto fixtures, which run for every test.
Related lessons: “Scope, auto and setup/teardown”, “Fixtures or a base test class”, “A minimal Page Object in Playwright”.
In an interview.Junior: Fixtures in Playwright are built-in DI: a test asks for a dependency in its arguments and the runner creates and cleans it up. I register Page Objects and API clients as fixtures, so tests have no new and no manual cleanup. Middle/Senior: The runner reads names from the destructuring, creates dependencies before dependants and tears down in reverse, and the code after use runs even after a failed test. Fixtures are lazy and combine through extend and mergeTests. It is not a full DI container: replacing an implementation goes through options, not interfaces.
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
Figure 1. The token is created and removed once per worker, the account is created and deleted in every test.
Which scope to choose
test
New for each test
Everything the test changes: an account, a page, data. Isolation matters more than speed.
worker
One per worker
Expensive and immutable resources: a token, a database connection, an unchanging reference.
Figure 2. Both scopes are legitimate, the choice depends on whether a test changes the resource.
Example: a token per worker, an account per test. Four important places are marked.
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));
awaituse();
// runs after every test even without a requestexpect(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 runconst user = awaitcreateUser('qa-w' + workerInfo.workerIndex);
awaituse(user);
awaitdeleteUser(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 page or 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.
Related lessons: “Fixtures: DI built into Playwright Test”, “Fixtures or a base test class”, “The alternative: a worker fixture instead of a Singleton”.
In an interview.Junior: Expensive immutable resources, such as a token or a connection, I make worker fixtures, and everything a test changes test fixtures with cleanup after use. I take auto fixtures only for cross-cutting things like logging. Middle/Senior: A worker fixture lives once per worker and cannot depend on test fixtures. After a failure the worker restarts, so setup must be repeatable and data unique through workerIndex. Teardown runs in reverse, so the token is still available to delete the account. For setup for the whole run there is globalSetup or a setup project.
Fixtures or a base test class
In Playwright, fixtures replace a base class with beforeEach: they are lazy, isolated and have a teardown even after a failure. A base class creates everything for every test, and variables in describe are shared state the compiler does not control. Fixtures are typed and combine through mergeTests; beforeEach stays for a simple local step with no cleanup.
Patterns · Fixtures
A colleague from Java moved BaseTest into Playwright: variables in describe and beforeEach. What is wrong here?
Java Selenium projects have a familiar pattern: a base test class with @BeforeEach where the driver and all pages are created, and tests inherit from it. A candidate carries this scheme over to Playwright: let loginPage variables in describe and filling them in beforeEach. The tests pass, but the benefits of fixtures are gone. This lesson compares both approaches on five criteria and shows where beforeEach is still appropriate.
How it works and why. A base class and hooks run for every test, regardless of whether it needs each object: the base creates everything that may be needed somewhere. Variables in describe are shared state that is overwritten before each test but belongs to the module. Fixtures work differently: a test asks for specific dependencies, the runner creates only those and cleans them up after each test. The difference is not cosmetic, it touches isolation, the cleanup guarantee and types.
A base class or fixtures
Wrong
describe + beforeEach
Everything is created for every test. Variables are shared, and the compiler does not know whether they are filled yet. Cleanup is in a separate hook.
Right
Fixtures
Laziness, isolation, types and cleanup together with creation. Several sets combine through mergeTests.
Figure 1. The same task, another responsibility of the runner.
Example: from beforeEach to fixtures. The starting point. Seemingly tidy until it has to be changed or extended. Four weak places are marked.
test.describe('payments', () => {
1let loginPage: LoginPage;
let paymentsPage: PaymentsPage;
let account: Account;
2 test.beforeEach(async ({ page, request }) => {
loginPage = newLoginPage(page);
paymentsPage = newPaymentsPage(page);
account = awaitcreateAccountViaApi(request);
});
3 test.afterEach(async ({ request }) => {
awaitdeleteAccountViaApi(request, account.id);
});
test('archive is visible', async () => {
// filled by beforeEach: the compiler does not check it4await loginPage.login(account.email, account.password);
});
});
The variables are declared without values: TypeScript believes they are filled, though that depends on the order of the hooks.
All pages and the account are created, even if the test needs only one of them.
Cleanup lies in a separate hook, far from what it cleans.
The test uses the variables as if they were always ready: an error in the hook shows up elsewhere.
Each of these flaws is small, but together they form a template that gets copied into every describe. Now with fixtures declared earlier in fixtures.ts (as in the lesson on DI):
// fixtures are declared once in fixtures.tsimport { test, expect } from'./fixtures';
test.describe('payments', () => {
test('archive is visible', async ({ loginPage, account }) => {
await loginPage.login(account.email, account.password);
});
test('empty state', async ({ loginPage }) => {
// account is not requested, so it is not createdawait loginPage.goto();
});
});
There are no variables and no hooks. The second test does not ask for account, so no account is created or deleted for it: on a large suite this saves API calls and time. Fixtures combine: a set of pages and a set of data live in different files and merge through mergeTests, while a base class can be inherited only once.
Why fixtures are better. First, laziness: only what is needed is created. Second, isolation: each test gets its own instances, not shared fields. Third, teardown together with creation, and it runs even on failure. Fourth, types: the test sees the type of each fixture in its arguments, not a variable that may be uninitialised. Fifth, fixtures can be configured with options (test.use), and that replaces method overriding in descendant classes.
Limits and alternatives.beforeEach remains appropriate for a simple step that concerns one file and needs no cleanup, such as opening the right page:
test.describe('settings', () => {
// a step for this file only: a fixture would be excessive
test.beforeEach(async ({ page }) => {
await page.goto('/settings');
});
});
The criterion: if the same beforeEach is copied into several files, creates something that must be cleaned up, or passes its result to tests through a variable, it is a candidate for a fixture. Hooks and fixtures can be combined: fixtures prepare objects, and beforeEach performs a local step. For expensive setup shared by a whole file there is beforeAll, but it lives within one worker and gives no test isolation, so a worker fixture is often better for it.
Common mistakes.
A describe-level variable filled by beforeEach: the compiler cannot tell "not yet filled" from "ready", and with a changed order or execution mode it easily becomes shared state.
One "universal" set in beforeEach for all tests: things the test does not use are created and the set gets slower.
Copying the same beforeEach into ten files: the change must be made in all of them, and one is always forgotten.
Carrying the BaseTest template from Java without changing the approach: Playwright has its own mechanism for this, and ignoring it means losing cleanup and isolation.
Check yourself
A describe declares let paymentsPage: PaymentsPage filled by beforeEach. Why is this code riskier than a fixture?
Answer
The variable belongs to the module, not to the test. The compiler considers it always filled, though that depends on the order of hooks, and any change of execution mode or a skipped hook leaves the old value from the previous test in it. A fixture is created anew and passed to exactly this test.
When is beforeEach better than a fixture?
Answer
When the step is simple, needed in one file only and creates no resources that must be cleaned up, for example opening the settings page. If the same hook is copied, returns a value into a variable or requires cleanup, it should move into a fixture.
Related lessons: “Fixtures: DI built into Playwright Test”, “Scope, auto and setup/teardown”, “A minimal Page Object in Playwright”, “Typical antipatterns in frameworks”.
In an interview.Junior: In Playwright I do not make a BaseTest, because fixtures give lazy creation, isolation and guaranteed cleanup. I keep beforeEach for simple steps within one file. Middle/Senior: A base class creates everything for all tests, and describe variables are shared state the compiler does not control. Fixtures are requested by the test, combine through extend and mergeTests, have types and a teardown after use that runs on failure too. A hook stays where the step is local and needs no cleanup; if it gets copied, it becomes a fixture.