| | |

Playwright 11 ๐ŸŽญ Test Fixtures โ€” test.extend and custom fixture injection

โฑ๏ธ Estimated read: 10 min | |

A Playwright test declares what it needs in its parameter list, and the runner prepares those dependencies before the test body runs. page, context, and browser are fixturesโ€”not globals. test.extend is the mechanism for adding a custom fixture to that system: a named setup/teardown unit that the test requests by name, that can depend on other fixtures, and whose teardown runs even when the test fails.

This chapter covers the test.extend API, the fixture lifecycle that separates setup from teardown with await use(), and the composition and scoping patterns that make a suite’s setup reusable without a beforeEach that runs for every test. The sections that follow walk through the custom fixture, the teardown contract, and the worker-scoped and option fixtures that address the cases a test-scoped fixture cannot.

Key point: A custom fixture is async ({ dependencies }, use) => { setup; await use(value); teardown }; the test requests it by name, the setup runs lazily before the test, and the teardown after use returns runs even when the test fails.


a. The custom fixture and the use boundary

test.extend takes a fixture type and an object of fixture definitions. Each fixture receives the fixtures it depends on (destructured from the first argument) and a use callback. Whatever is passed to use is what the test receives when it requests the fixture. The code before use is the setup; the code after it is the teardown.

import { test as base } from "@playwright/test";

type MyFixtures = {
  seededUser: { email: string };
};

export const test = base.extend<MyFixtures>({
  seededUser: async ({}, use) => {
    const user = { email: "ana@example.com" }; // setup
    await use(user);                            // test runs here
    // teardown, if any, goes here
  },
});

The test imports test from the fixtures file and requests the fixture by name in its parameter list. The fixture is lazy: it runs only for the test that asks for it, not for every test in the file.

import { test, expect } from "./fixtures";

test("shows the seeded user", async ({ page, seededUser }) => {
  await page.goto(`/users/${seededUser.email}`);
  await expect(page.getByRole("heading")).toBeVisible();
});

The empty destructure async ({}, use) is the idiomatic form for a fixture with no dependencies, but ESLint’s no-empty-pattern rule flags it. The fix is an inline disable or a dependency on a built-in fixture that the setup actually uses . The empty shape is the correct syntax; hiding it with a workaround obscures the fact that it is a fixture.


b. Teardown is the whole point

The await use(value) call is the split between setup and teardown. Everything before it runs before the test; everything after it runs after the test, even when the test throws. A fixture that creates a resource must release it after use, and the release must be awaited.

tempOrder: async ({ request }, use) => {
  const response = await request.post("/api/orders", { data: { customer: "Test" } });
  const order = await response.json();

  await use(order); // the test runs with the order

  await request.delete(`/api/orders/${order.id}`); // teardown
};

The failure mode that costs a day is the missing teardown. The next test inherits the state the previous test left behind, and the symptom looks like flakiness. The cause is the missing release, and the fix is the line after use . The unawaited teardown is worse: Playwright thinks the fixture is done and starts the next test, and the teardown races against the next test’s setup.

The teardown is also the place for a resource that the test does not release itself. A fixture that opens a database connection closes it after use; a fixture that starts a server stops it after use. The test body does not need to know about the lifecycle.


c. Composition, scoping, and the option fixture

A fixture can depend on another fixture, and the dependency is resolved before the fixture’s setup runs. This composition is the mechanism for building a higher-level fixture from a lower-level oneโ€”an authenticated page that depends on the credentials fixture, an API client that depends on a token fixture.

apiClient: async ({ playwright }, use) => {
  const context = await playwright.request.newContext({
    baseURL: "http://localhost:3000",
  });
  await use(context);
  await context.dispose(); // teardown
};

The authenticatedRequest fixture from the same pattern creates an APIRequestContext carrying the session cookie, and any test that requests it gets the authenticated context without re-logging in . The caller does not read the storage state file or create the context; the fixture composition does it.

A fixture’s default scope is test-scoped: a fresh instance per test, torn down after the test. The { scope: "worker" } option makes it worker-scoped: one instance per worker process, shared across the tests in that worker, torn down when the worker exits. The worker scope is the pattern for an expensive resourceโ€”a database connection, a seeded accountโ€”that every test in the worker can share.

sharedAccount: [async ({}, use) => {
  const account = await createAccount();
  await use(account);
  await deleteAccount(account);
}, { scope: "worker" }],

The { auto: true } option makes a fixture run for every test in the file, even when the test does not request it. It is the replacement for a beforeEach that must run unconditionally, and it is the pattern for a fixture that seeds the database or resets the server before every test .

The option fixture is a configuration value that the test file or the project config can override. It is declared with { option: true } and a default value, and a fixture that depends on it reads the current value.

type Options = { defaultUser: { email: string; password: string } };

export const test = base.extend<Options>({
  defaultUser: [{ email: "user@example.com", password: "pass" }, { option: true }],
});

The config’s use block overrides the option for a project, and test.use({ defaultUser: ... }) overrides it for a test file or a describe block. The option is the mechanism for a fixture whose behavior differs between the local and CI runs or between the roles a suite tests .


Complete Example Session

// ============================================
// PART 1: THE FIXTURES FILE
// ============================================
// fixtures.ts
import { test as base } from "@playwright/test";

type MyFixtures = {
  seededUser: { email: string; password: string };
  authenticatedPage: import("@playwright/test").Page;
  tempOrder: { id: string };
};

export const test = base.extend<MyFixtures>({
  // Simple value fixture
  seededUser: async ({}, use) => {
    await use({ email: "ana@example.com", password: "secret" });
  },

  // Composed fixture: depends on seededUser and page
  authenticatedPage: async ({ page, seededUser }, use) => {
    await page.goto("/login");
    await page.getByLabel("Email").fill(seededUser.email);
    await page.getByLabel("Password").fill(seededUser.password);
    await page.getByRole("button", { name: "Sign in" }).click();
    await page.waitForURL("/dashboard");

    await use(page); // the test gets the authenticated page

    await page.goto("/logout"); // teardown
  },

  // Resource fixture with teardown
  tempOrder: async ({ request }, use) => {
    const res = await request.post("/api/orders", { data: { customer: "Test" } });
    const order = await res.json();
    await use(order);
    await request.delete(`/api/orders/${order.id}`);
  },
});

// ============================================
// PART 2: THE TEST
// ============================================
// dashboard.spec.ts
import { test, expect } from "./fixtures";

test("shows the dashboard for the authenticated user", async ({ authenticatedPage }) => {
  await expect(authenticatedPage.getByRole("heading", { name: "Dashboard" })).toBeVisible();
});

test("creates and cleans up an order", async ({ tempOrder }) => {
  expect(tempOrder.id).toBeDefined();
});

// ============================================
// PART 3: THE WORKER-SCOPED FIXTURE
// ============================================
export const testWithWorker = base.extend<{}, { sharedToken: string }>({
  sharedToken: [async ({}, use) => {
    const token = await fetchToken(); // once per worker
    await use(token);
  }, { scope: "worker" }],
});

The parts covered the fixture file with a value fixture, a composed fixture, and a resource fixture with teardown, the test that requests them by name, and the worker-scoped variant.


Quick Reference

Fixture Anatomy

PartCode
Declarationtest.extend<Fixtures>({ ... })
Fixture functionasync ({ deps }, use) => { ... }
SetupCode before await use(value)
TestRuns at await use(value)
TeardownCode after await use(value)

Scopes and Options

OptionEffect
(default)Test-scoped, fresh per test
{ scope: "worker" }Shared per worker
{ auto: true }Runs for every test
{ option: true }Configurable via test.use

Built-in Fixtures

FixtureProvides
pageIsolated page per test
contextIsolated context per test
browserShared browser per worker
requestAPI request context

Best Practices

โœ… Do This:

// Await the use call and the teardown
await use(value);
await resource.dispose();                                     // โœ…

// Compose fixtures for higher-level setup
authenticatedPage: async ({ page, user }, use) => { ... }     // โœ…

// Use worker scope for expensive shared resources
{ scope: "worker" }                                           // โœ…

โŒ Don’t Do This:

// Skip the teardown
await use(value); // no cleanup                                // โŒ

// Forget to await the teardown
use(value); resource.dispose(); // races the next test         // โŒ

// Use beforeEach for state only one test needs
test.beforeEach(async ({ page }) => { ... });                  // โŒ

Common Pitfalls

PitfallWhy It HappensFix
State leaks between testsNo teardown after useAdd the teardown and await it
Teardown races the next testTeardown not awaitedawait the teardown
Fixture runs for every testauto: true without needRemove the option or use test scope
Option not overriddenoption: true missingAdd the option flag

Real-World Examples

1. Value fixture

seededUser: async ({}, use) => { await use({ email: "a@b.com" }); }

2. Composed fixture

authenticatedPage: async ({ page, user }, use) => {
  await page.goto("/login");
  // login
  await use(page);
}

3. Resource fixture with teardown

tempOrder: async ({ request }, use) => {
  const order = await create();
  await use(order);
  await request.delete(`/orders/${order.id}`);
}

4. Worker scope

sharedToken: [async ({}, use) => { ... }, { scope: "worker" }]

5. Auto fixture

setupDb: [async ({}, use) => { ... }, { auto: true }]

6. Option fixture

defaultUser: [{ email: "a@b.com" }, { option: true }]

7. Override the option

test.use({ defaultUser: { email: "admin@b.com" } });

8. Page object as a fixture

loginPage: async ({ page }, use) => { await use(new LoginPage(page)); }

9. API client fixture

api: async ({ playwright }, use) => {
  const ctx = await playwright.request.newContext();
  await use(ctx);
  await ctx.dispose();
}

10. Worker index for isolation

dbUser: async ({}, use, testInfo) => {
  await use(`user-${testInfo.workerIndex}`);
}

Visual

The Fixture Lifecycle

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Test requests fixture                                  โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Setup (code before use)                                โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  await use(value) โ”€โ”€โ–บ Test body runs                    โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Teardown (code after use)                              โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Fixture torn down                                      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Fixture Composition

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  seededUser (no deps)                                   โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  authenticatedPage (depends on page + seededUser)       โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Test requests authenticatedPage                        โ”‚
โ”‚  โ†’ page, seededUser, then authenticatedPage            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Scopes

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  TEST SCOPE                     WORKER SCOPE            โ”‚
โ”‚                                                         โ”‚
โ”‚  Fresh per test                 Shared per worker       โ”‚
โ”‚  Torn down after test           Torn down at worker end โ”‚
โ”‚  page, context                  database, account       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Teardown Gap

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  WITHOUT teardown                                       โ”‚
โ”‚  Test 1 creates order โ†’ test ends                       โ”‚
โ”‚  Test 2 sees the order โ†’ flaky                          โ”‚
โ”‚                                                         โ”‚
โ”‚  WITH teardown                                          โ”‚
โ”‚  Test 1 creates order โ†’ test ends โ†’ order deleted       โ”‚
โ”‚  Test 2 starts clean                                    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Extendtest.extend<Fixtures>({ ... })
Fixture functionasync ({ deps }, use) => { ... }
SetupBefore await use
TeardownAfter await use
Scope{ scope: "worker" }
Auto{ auto: true }
Option{ option: true }
CompositionFixtures depend on fixtures

Key takeaways:

  • A fixture is a named setup/teardown unit. The test requests it by name, the setup runs before the test, and the teardown runs after use returnsโ€”even when the test fails. The code before use is the setup; the code after is the teardown .
  • The teardown is the contract, not an afterthought. A fixture that creates a resource must release it after use, and the release must be awaited. A missing or unawaited teardown produces state that leaks into the next test and failures that look like flakiness.
  • Composition builds higher-level fixtures. A fixture can depend on another fixture, and the dependency is resolved before its setup runs. The authenticated page, the API client with a token, and the page object are all compositions of built-in or lower-level fixtures.
  • The scope and the option change the lifecycle. The default is test-scoped; { scope: "worker" } shares the fixture per worker, { auto: true } runs it for every test, and { option: true } makes it configurable through test.use and the project config .
  • The fixture is the replacement for beforeEach when the setup is composable. A beforeEach runs for every test whether or not the test needs the setup; a fixture runs only when the test requests it, and its teardown is guaranteed.

Remember: A Playwright test is a declaration of what it needs, and the fixtures are the things it needs. test.extend adds a new fixture to the system, and the use boundary is the setup/teardown split. Put the resource creation before use, the release after it, and the await on both. Compose the fixtures for the higher-level setup, scope them when the resource is expensive, and never rely on a beforeEach for a setup that only one test requires.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!