Fixtures: DI built into Playwright Test
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
Who is responsible for creation and cleanup
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.
The test asks for a fixture
Creation and deletion are described once. The test contains only the scenario, and teardown always runs.
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 = new LoginPage(page);
const paymentsPage = new PaymentsPage(page);
const account = await createAccountViaApi(request);
await loginPage.goto();
await loginPage.login(account.email, account.password);
await expect(paymentsPage.archived.rowByText('INV-1')).toBeVisible();
// will not run if the expect above threw
await deleteAccountViaApi(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';
type Pages = { loginPage: LoginPage; paymentsPage: PaymentsPage };
type Data = { account: Account };
1export const test = base.extend<Pages & Data>({
2 loginPage: async ({ page }, use) => {
await use(new LoginPage(page));
},
paymentsPage: async ({ page }, use) => {
await use(new PaymentsPage(page));
},
account: async ({ request }, use) => {
const account = await createAccountViaApi(request);
3 await use(account);
// runs after a failed test as well
4 await deleteAccountViaApi(request, account.id);
},
});
export { expect } from '@playwright/test';
base.extendwith a type: TypeScript knows which fixtures exist and what they return.- The fixture depends on
page, so the runner creates it afterpage. usepasses the value to the test and suspends the fixture until the test ends.- The code after
useis teardown: the account is always deleted.
The test now describes only the scenario:
test('archived payment is visible', async ({
loginPage,
paymentsPage,
account,
}) => {
await loginPage.goto();
await loginPage.login(account.email, account.password);
await expect(paymentsPage.archived.rowByText('INV-1')).toBeVisible();
});
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';
export const 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.useis 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.