Skip to main content

Fixtures with test.extend

Why This Matters

beforeEach works until tests need different setups. Some need the shop open, some need two products in the cart, some need an API client, some need all three. Fixtures are Playwright’s answer: each test asks for what it needs by name, Playwright builds exactly that (and what it depends on), and cleans up afterwards, even when the test fails.

You have used fixtures all along

page, request, context and baseURL are fixtures. When a test says async ({ page }) => …, Playwright creates a page for it, and closes it afterwards. test.extend adds your own.

The shop’s fixtures

tests/fixtures/shop.ts:

export const test = apiTest.extend<ShopFixtures, WorkerFixtures>({
  shop: async ({ page }, use) => {
    const shop = new ShopPage(page);
    await shop.goto();
    await use(shop);
  },

  checkoutWithTwo: async ({ shop }, use) => {
    await shop.addToCart("Bluetooth Headphones");
    await shop.addToCart("Desk Lamp");
    await expect(shop.cartButton).toContainText("2 items");
    await use(await shop.openCart());
  },
  // ...
});

A fixture is an async function with three parts:

  1. Setup: everything before use(...).
  2. use(value): hands the value to the test and waits until the test is done.
  3. Teardown: everything after use(...). It runs after the test, also when the test failed.

Fixtures depend on each other by name: checkoutWithTwo asks for shop, which asks for page. A test that asks for checkoutWithTwo gets all three, built in the right order.

Only what a test asks for

Fixtures are lazy. In tests/module-7/cart.spec.ts:

test("search finds one product", { tag: "@smoke" }, async ({ shop }) => { /* ... */ });
test("removing a product leaves the other one", async ({ checkoutWithTwo }) => { /* ... */ });

The first test gets an open shop and nothing else. The second also gets two products in the cart and the checkout open. Neither pays for setup it does not need, which beforeEach cannot do.

Building on other fixtures

The shop fixtures extend the API fixture from module 4:

import { expect, test as apiTest } from "./api";

export const test = apiTest.extend<ShopFixtures, WorkerFixtures>({ /* ... */ });

So a test that imports test from fixtures/shop.ts can ask for api, sandboxId, shop, checkoutWithTwo and catalog. For two fixture files that do not build on each other, Playwright offers mergeTests(testA, testB).

Test scope and worker scope

By default a fixture is created for every test. A worker-scoped fixture is created once per worker process and shared by all tests in that worker:

catalog: [
  async ({ playwright }, use) => {
    const api = await playwright.request.newContext({ baseURL: `${BASE_URL}/api/shop/` });
    const body = ProductListSchema.parse(await (await api.get("products", { params: { limit: 50 } })).json());
    await api.dispose();
    await use(body.items);
  },
  { scope: "worker" },
],

Use worker scope for read-only data that is expensive to fetch: the product catalogue, a configuration, a list of countries. Never for anything a test changes, because the next test in that worker would see the change. A worker fixture can only depend on other worker fixtures; that is why it uses BASE_URL from src/env.ts and not the test-scoped baseURL.

The catalogue then lets a test calculate its expectation instead of hard-coding it:

test("the checkout total matches the catalogue prices plus tax", async ({ checkoutWithTwo, catalog }) => {
  const price = (name: string) => catalog.find((p) => p.name === name)!;
  const expected = totalPrice([
    { product: price("Bluetooth Headphones"), quantity: 1 },
    { product: price("Desk Lamp"), quantity: 1 },
  ]);
  await expect(checkoutWithTwo.total).toHaveText(`$${expected.toFixed(2)}`);
});

If the shop changes a price, this test still checks the right sum, with the totalPrice() helper from module 1.

Exercise

Write a fixture orderedLamp that places an order for one Desk Lamp through the API (in the test’s own sandbox, with the api fixture) and hands the test the order. In its teardown, cancel the order. Why is the teardown in the fixture better than at the end of the test?

Show suggested solution
orderedLamp: async ({ api }, use) => {
  await api.post("cart/items", { data: { productId: 9 } });
  const placed = OrderSchema.parse(await (await api.post("orders", { data: orderRequest })).json());
  await use(placed);
  await api.post(`orders/${placed.id}/cancel`);
},

orderRequest is the billing and payment object from tests/module-4/orders.api.spec.ts (called order there), moved to a shared file.

Code after use() runs even when the test fails halfway. Cleanup at the end of a test body is skipped the moment an assertion fails, which is exactly when leftovers cause the next test to fail for a reason that has nothing to do with it.