Playwright NotesRohit’s interview study guide
Chapter 07

Test Structure, Fixtures and the Page Object Model

How a test file is organised (describe blocks, hooks, serial and parallel groups, steps), how Playwright's fixtures set things up and tear them down around each test, how to write your own, how to build page objects for the Practice Shop, when to reach for a fixture, a page object or a plain helper, and how to keep test data isolated. Every test was run with Playwright 1.65.1 against the Practice Shop.

7 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#Hooks and describe blocks

Added

A test file is more than a list of test(...) calls. test.describe groups tests under a shared title, and hooks run code around them: beforeEach and afterEach around every test in the group, beforeAll and afterAll once around the whole group. Groups can nest, and an inner group's hooks run inside the outer group's.

The mental model is layers of an onion. The outermost layer is the file, then each describe, then the test itself. Before a test, Playwright walks inwards running every beforeEach it passes; after the test, it walks back outwards running the afterEach hooks in reverse. beforeAll and afterAll wrap the whole onion once, not each test.

One thing surprises almost everyone: beforeAll runs once per worker process, not once per file or per run. If a worker crashes or a test fails, Playwright throws that worker away and starts a new one, and beforeAll runs again in it. So beforeAll is the wrong place for "do this exactly once for the whole suite" (that's globalSetup or a setup project, Chapter 8), and it should never leave state that a later test depends on.

Here's every hook printing when it runs, so the order is visible:

tests/hooks.spec.ts
import { test, expect } from "@playwright/test";

test.beforeAll(async () => {
  console.log("beforeAll (file)");
});
test.afterAll(async () => {
  console.log("afterAll (file)");
});

test.beforeEach(async ({ page }, testInfo) => {
  console.log(`  beforeEach (file): ${testInfo.title}`);
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
});
test.afterEach(async ({}, testInfo) => {
  console.log(`  afterEach (file): ${testInfo.title} → ${testInfo.status}`);
});

test("shows all eight products", async ({ page }) => {
  console.log("    test body");
  await expect(page.getByRole("listitem")).toHaveCount(8);
});

test.describe("search", () => {
  test.beforeEach(async ({ page }) => {
    console.log("    beforeEach (search)");
    await expect(page.getByRole("listitem")).toHaveCount(8);
  });

  test("finds the mouse", async ({ page }) => {
    console.log("      test body");
    await page.getByLabel("Search products").fill("wireless");
    await expect(page.getByRole("listitem")).toHaveText([/Wireless Mouse/]);
  });

  test("says when nothing matches", async ({ page }) => {
    console.log("      test body");
    await page.getByLabel("Search products").fill("banana");
    await expect(page.getByText("No products match “banana”.")).toBeVisible();
  });
});
npx playwright test
Running 3 tests using 1 worker

beforeAll (file)
  beforeEach (file): shows all eight products
    test body
  afterEach (file): shows all eight products → passed
  ✓  1 [chromium] › tests/hooks.spec.ts:21:1 › shows all eight products (1.5s)
  beforeEach (file): finds the mouse
    beforeEach (search)
      test body
  afterEach (file): finds the mouse → passed
  ✓  2 [chromium] › tests/hooks.spec.ts:32:3 › search › finds the mouse (2.2s)
  beforeEach (file): says when nothing matches
    beforeEach (search)
      test body
  afterEach (file): says when nothing matches → passed
afterAll (file)
  ✓  3 [chromium] › tests/hooks.spec.ts:38:3 › search › says when nothing matches (2.2s)

  3 passed (6.4s)
What’s happening
  1. beforeAll (file) prints once, before the first test: one file, one worker, so one beforeAll. afterAll (file) prints once at the very end, after the last afterEach (the reporter happens to print the third test's ✓ line just after it; the console lines are in true order).
  2. Every test gets the file's beforeEach first. It uses the page fixture and signs in, so each test starts signed in on the products page, in its own fresh context. Nothing is shared between the three tests except what the code itself shares.
  3. The two tests inside describe("search") also get the group's own beforeEach, which runs after the file's one (outside in). It waits for the eight products, so a search never starts before the list has loaded.
  4. afterEach sees the result: testInfo.status is passed for each. An afterEach is the place for per-test reporting or attaching extra evidence on failure (if (testInfo.status !== testInfo.expectedStatus) …).
  5. The describe title becomes part of each test's name (search › finds the mouse), which is how you'd filter them: npx playwright test -g "search".
  6. If you changed the first test to fail, its worker would be replaced (per the docs, "worker process is restarted on test failures"), and beforeAll (file) would print a second time before the next test. A quick three-test file whose first test fails, run while writing this page, printed beforeAll twice. That's why beforeAll must never be "run once per suite" logic.
AdvancedSerial groups: when tests share one page

By default tests in one file run one after another in one worker, but each is independent: a failure in one doesn't stop the others. test.describe.configure({ mode: "serial" }) changes that: the group's tests always run together, in order, and if one fails, the rest are skipped. The docs call it discouraged ("it is usually better to make your tests isolated"), and the old spelling test.describe.serial is deprecated.

It exists for the rare journey where splitting into tests that share one page really is the clearest way to report it. Here a group shares a single page across three tests, and the second test is wrong on purpose:

tests/serial.spec.ts
import { test, expect, type Page } from "@playwright/test";

test.describe.configure({ mode: "serial" });

let page: Page;

test.beforeAll(async ({ browser }) => {
  page = await browser.newPage();
});
test.afterAll(async () => {
  await page.close();
});

test("sign in", async () => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page.getByText("Signed in as rohit")).toBeVisible();
});

test("add two products", async () => {
  await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
  // Wrong on purpose: only one product was added.
  await expect(page.getByRole("link", { name: "Cart (2)" })).toBeVisible({ timeout: 2000 });
});

test("check out", async () => {
  await page.getByRole("link", { name: /Cart/ }).click();
  await page.getByRole("link", { name: "Checkout" }).click();
  await expect(page.getByRole("heading", { name: "Checkout" })).toBeVisible();
});
npx playwright test
Running 3 tests using 1 worker

  ✓  1 [chromium] › tests/serial.spec.ts:14:1 › sign in (957ms)
  ✘  2 [chromium] › tests/serial.spec.ts:22:1 › add two products (2.8s)
  -  3 [chromium] › tests/serial.spec.ts:28:1 › check out


  1) [chromium] › tests/serial.spec.ts:22:1 › add two products ─────────────────────────────────────

    Error: expect(locator).toBeVisible() failed

    Locator: getByRole('link', { name: 'Cart (2)' })
    Expected: visible
    Timeout: 2000ms
    Error: element(s) not found

    Call log:
      - Expect "toBeVisible" getByRole('link', { name: 'Cart (2)' }) with timeout 2000ms
      - waiting for getByRole('link', { name: 'Cart (2)' })


      23 |   await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
      24 |   // Wrong on purpose: only one product was added.
    > 25 |   await expect(page.getByRole("link", { name: "Cart (2)" })).toBeVisible({ timeout: 2000 });
         |                                                              ^
      26 | });
      27 |
      28 | test("check out", async () => {
        at <project>/tests/serial.spec.ts:25:62

    Error Context: test-results/serial-add-two-products-chromium/error-context.md

    Error Context: test-results/serial-add-two-products-chromium/error-context.md

  1 failed
    [chromium] › tests/serial.spec.ts:22:1 › add two products ──────────────────────────────────────
  1 did not run
  1 passed (4.2s)
What’s happening
  1. beforeAll takes the browser fixture (worker-scoped, so allowed in beforeAll) and opens one page for the whole group. The three tests share it through the module variable page; none of them asks for the usual page fixture. A page made this way still gets the config's use options, which is why goto("/practice/") works with the baseURL.
  2. "sign in" passes and leaves the shared page signed in on the products page. That state is exactly what the next test relies on: this is order dependence, on purpose.
  3. "add two products" adds one product and then waits for "Cart (2)", which never appears, so it fails after 2 seconds. That's the deliberate mistake.
  4. "check out" didn't run: serial mode skipped it (the - mark), because the page it needs is in an unknown state. The summary shows 1 failed, 1 did not run and 1 passed. (The "Error Context" line really is printed twice in this run; it's the reporter's output, not a typo.)
  5. With retries on, Playwright would retry the whole group from "sign in", not just the failed test. That's the cost of serial mode: one failure hides everything after it, and retries are slower. The default (independent tests, each doing its own setup through a fixture) avoids both.
AdvancedRunning a file's tests in parallel

The opposite switch, test.describe.configure({ mode: "parallel" }), lets the tests of one file run at the same time in different workers (the config's fullyParallel: true does the same for every file). It only works if every test is independent, which is one more reason to never write the serial pattern above by accident. Chapter 12 covers workers in depth.

Advancedtest.step: naming the parts of a long test

A long journey test (sign in, add, check out) can fail anywhere, and "line 37" isn't a great report. test.step(title, body) groups actions under a name that appears in the HTML report, the trace viewer and, with printSteps, in the terminal. A step returns whatever its body returns. Options added later: box (1.39) points errors at the step call instead of the line inside it, timeout (1.50), and subtitle and params (1.63).

playwright.config.ts
import { defineConfig, devices } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  reporter: [["list", { printSteps: true }]],
  use: { baseURL: "https://rohit-playwright.pages.dev" },
  projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
});
tests/journey.spec.ts
import { test, expect } from "@playwright/test";

test("buy a keyboard", async ({ page }) => {
  await test.step("sign in as rohit", async () => {
    await page.goto("/practice/");
    await page.getByLabel("Username").fill("rohit");
    await page.getByLabel("Password").fill("playwright");
    await page.getByRole("button", { name: "Sign in" }).click();
  });

  const total = await test.step("add the keyboard and open the cart", async () => {
    await page.getByRole("listitem").filter({ hasText: "Compact Keyboard" }).getByRole("button", { name: "Add to cart" }).click();
    await page.getByRole("link", { name: "Cart (1)" }).click();
    return page.getByTestId("cart-total").textContent();
  });

  await test.step("check out", async () => {
    await page.getByRole("link", { name: "Checkout" }).click();
    await page.getByLabel("Email").fill("rohit@example.com");
    await page.getByLabel("Delivery address").fill("12 Long Street, Toronto");
    await page.getByLabel("I agree to the terms").check();
    await page.getByRole("button", { name: "Place order" }).click();
  });

  await expect(page.getByText(`Total paid on delivery: ${total}`)).toBeVisible();
});
npx playwright test
Running 1 test using 1 worker

     1.1 [chromium] › tests/journey.spec.ts:3:1 › buy a keyboard › sign in as rohit (153ms)
     1.2 [chromium] › tests/journey.spec.ts:3:1 › buy a keyboard › add the keyboard and open the cart (1.4s)
     1.3 [chromium] › tests/journey.spec.ts:3:1 › buy a keyboard › check out (114ms)
  ✓  1 [chromium] › tests/journey.spec.ts:3:1 › buy a keyboard (3.0s)

  1 passed (3.4s)
What’s happening
  1. printSteps: true makes the list reporter print a line for each test.step as it finishes, numbered under its test (1.1, 1.2, 1.3) and with its own time, before the test's own ✓ line. Without it you'd see only the test line (the steps still appear in the HTML report and trace).
  2. The second step returns a value: the cart total text ("$59.00"). test.step resolves to whatever its body returns, so steps can hand data to later code without a module variable.
  3. Steps are only labels around normal code: there's no extra waiting or retrying, and a failure inside a step fails the test as usual, with the step's name in the report so you can see where in the journey it broke. Notice "check out" takes only about a tenth of a second: clicking Place order returns at once, and the 1.2-second wait for the order happens in the final expect, outside any step. A step times exactly the code inside it.
  4. Use steps for long journeys and inside page-object methods and fixtures (a signIn() method wrapped in a step reads as one line in the report). Don't use them to split what should be separate tests.

#How fixtures work

Added

When you write async ({ page }) => …, you're asking for a fixture: a named thing the test needs, which Playwright sets up before the test, hands to it, and tears down after it. page, context, browser, browserName and request are built-in fixtures; you can add your own. The test lists what it needs in its first argument, and Playwright works out the rest.

A fixture is an async function with a use call in the middle, async ({ …fixtures it needs }, use) => { …; await use(value); … }. The code before await use(value) is the setup; the test runs during use, receiving value; the code after it is the teardown, and it runs whether the test passed or failed.

The mental model is a hotel room. You book what you need by name ({ page }); the hotel prepares it before you arrive (setup), you use it (the test), and housekeeping cleans it after you leave (teardown), even if you left in a hurry (a failed test). You only get what you booked: a fixture nobody asks for is never set up. And some things are shared by the whole floor (the browser, worker-scoped) while others are yours alone (the page, test-scoped).

The rules, from the docs: a fixture is set up only when a test (or a hook, or another fixture) asks for it; if fixture A needs B, B is set up first and torn down last; test-scoped fixtures are torn down after each test; worker-scoped ones when the worker shuts down. Here they are proven by fixtures that print:

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

type TestFixtures = { cart: string; account: string; logged: void };
type WorkerFixtures = { server: string };

export const test = base.extend<TestFixtures, WorkerFixtures>({
  server: [async ({}, use) => {
    console.log("setup    server (worker)");
    await use("http://shop.test");
    console.log("teardown server (worker)");
  }, { scope: "worker" }],

  account: async ({ server }, use) => {
    console.log("setup    account");
    await use(`rohit@${new URL(server).host}`);
    console.log("teardown account");
  },

  cart: async ({ account }, use) => {
    console.log("setup    cart");
    await use(`cart of ${account}`);
    console.log("teardown cart");
  },

  logged: [async ({}, use, testInfo) => {
    console.log(`-- start: ${testInfo.title}`);
    await use();
    console.log(`-- end:   ${testInfo.title}`);
  }, { auto: true }],
});
tests/order.spec.ts
import { test } from "../fixtures";

test("uses the cart", async ({ cart }) => {
  console.log(`   test body: ${cart}`);
});

test("uses only the account", async ({ account }) => {
  console.log(`   test body: ${account}`);
});

test("uses nothing", async () => {
  console.log("   test body");
});
npx playwright test
Running 3 tests using 1 worker

-- start: uses the cart
setup    server (worker)
setup    account
setup    cart
   test body: cart of rohit@shop.test
teardown cart
teardown account
-- end:   uses the cart
  ✓  1 [chromium] › tests/order.spec.ts:3:1 › uses the cart (0ms)
-- start: uses only the account
setup    account
   test body: rohit@shop.test
teardown account
-- end:   uses only the account
  ✓  2 [chromium] › tests/order.spec.ts:7:1 › uses only the account (0ms)
-- start: uses nothing
   test body
-- end:   uses nothing
  ✓  3 [chromium] › tests/order.spec.ts:11:1 › uses nothing (0ms)
teardown server (worker)

  3 passed (221ms)
What’s happening
  1. base.extend<TestFixtures, WorkerFixtures>({...}) returns a new test function that knows four extra fixtures. Tests import test from fixtures.ts instead of @playwright/test; everything built in (page, expect's retries, the config) still works.
  2. "uses the cart" asks only for cart. Playwright sees cart needs account, which needs server, so it sets them up dependencies first: server, account, cart. Teardown runs in reverse: cart, then account. The server isn't torn down after the test, because it's worker-scoped.
  3. "uses only the account" never mentions cart, so the cart fixture doesn't run at all (lazy). The server is already up from the first test, so only account is set up and torn down.
  4. "uses nothing" gets no custom fixtures except logged, which has { auto: true }: auto fixtures run for every test whether it asks or not. Its lines wrap each test, outermost, because it was set up first.
  5. teardown server (worker) prints once, after the last test, when the worker shuts down. A worker-scoped fixture is shared by every test that worker runs: set up once, reused, torn down at the end.
  6. Every fixture's code after await use(...) is its teardown, and it runs even if the test fails. That's the big advantage over afterEach: setup and cleanup live together, and cleanup only runs for fixtures that were actually set up.
AdvancedThe built-in fixtures, and how they connect

The built-in fixtures are fixtures like any other, defined the same way inside Playwright: browser is worker-scoped (one browser process per worker, shared), context is test-scoped (a fresh incognito-style profile per test), page is test-scoped and lives in that context, and request is a separate, isolated API client for the test with its own cookies. Config options such as baseURL, viewport or storageState are option fixtures too, which is how test.use({ … }) can change them per file.

tests/builtins.spec.ts
import { test, expect } from "@playwright/test";

test("how the built-in fixtures relate", async ({ page, context, browser, browserName, request }) => {
  console.log("page belongs to context:", page.context() === context);
  console.log("context belongs to browser:", context.browser() === browser);
  console.log("browserName:", browserName, "| pages in context:", context.pages().length);

  const res = await request.get("/practice/api/products.json");
  console.log("request fixture:", res.status(), (await res.json()).length, "products");

  await page.goto("/practice/");
  await expect(page).toHaveTitle("Sign in · Practice Shop");
});
npx playwright test
Running 1 test using 1 worker

page belongs to context: true
context belongs to browser: true
browserName: chromium | pages in context: 1
request fixture: 200 8 products
  ✓  1 [chromium] › tests/builtins.spec.ts:3:1 › how the built-in fixtures relate (82ms)

  1 passed (407ms)
What’s happening
  1. The test asks for all five built-ins. page.context() === context and context.browser() === browser are both true: the page fixture is created inside the context fixture, which is created in the worker's browser.
  2. The context has exactly one page, the test's own. A test that opens a popup or calls context.newPage() gets more pages in the same context, sharing its storage.
  3. browserName is chromium because the default config's only project is Desktop Chrome. Tests can use it to skip something per browser (test.skip(browserName === "webkit", "…")).
  4. request fetched the products JSON without any browser page: status 200 and 8 products, using baseURL. Chapter 9 is all about this fixture.
  5. Because page depends on context, which depends on browser, asking for just { page } (the usual case) sets up all three. You never need to ask for context unless you use it.

#Writing your own fixtures

Added

Chapter 3's checkout tests started with a helper, signInWithCart(page, ...products), and a promise: Chapter 7 turns this into a fixture. Here it is. The idea: a test should declare the state it starts in, not build it. A fixture builds it, the test just asks.

The design: two option fixtures, user and cartItems, say who is signed in and what's in the cart (defaults: rohit, empty). They're plain values that a file or describe can change with test.use({ … }), or a project can set in the config. Two normal fixtures build the state from them: signedIn signs in as user and hands over the page; atCheckout builds on signedIn, adds cartItems, and opens the checkout.

fixtures.ts
import { test as base, expect, type Page } from "@playwright/test";

type Options = { user: string; cartItems: string[] };
type Fixtures = { signedIn: Page; atCheckout: Page };

export const test = base.extend<Options & Fixtures>({
  // Options: values a test file or project can change with test.use() or in the config.
  user: ["rohit", { option: true }],
  cartItems: [[], { option: true }],

  // Signed in as `user`, on the products page.
  signedIn: async ({ page, user }, use) => {
    await page.goto("/practice/");
    await page.getByLabel("Username").fill(user);
    await page.getByLabel("Password").fill("playwright");
    await page.getByRole("button", { name: "Sign in" }).click();
    await expect(page.getByText(`Signed in as ${user}`)).toBeVisible();
    await use(page);
  },

  // Signed in, `cartItems` in the cart, on the checkout page.
  atCheckout: async ({ signedIn: page, cartItems }, use) => {
    for (const name of cartItems) {
      await page.getByRole("listitem").filter({ hasText: name }).getByRole("button", { name: "Add to cart" }).click();
    }
    await expect(page.getByRole("link", { name: `Cart (${cartItems.length})` })).toBeVisible();
    await page.goto("/practice/checkout");
    await use(page);
  },
});

export { expect };
tests/checkout.spec.ts
import { test, expect } from "../fixtures";
import type { Page } from "@playwright/test";

// A plain helper: no setup or teardown, just a few lines the tests repeat.
async function fillDetails(page: Page) {
  await page.getByLabel("Email").fill("rohit@example.com");
  await page.getByLabel("Delivery address").fill("12 Long Street, Toronto");
  await page.getByLabel("I agree to the terms").check();
}

test.describe("with a mouse in the cart", () => {
  test.use({ cartItems: ["Wireless Mouse"] });

  test("a signed-in user can buy a product and sees a confirmation", async ({ atCheckout: page }) => {
    await expect(page.getByLabel("Full name")).toHaveValue("Rohit");
    await fillDetails(page);

    await page.getByRole("button", { name: "Place order" }).click();

    await expect(page.getByRole("heading", { level: 1 })).toHaveText("Thank you, Rohit!");
    await expect(page.getByText("Total paid on delivery: $29.50")).toBeVisible();
  });
});

test.describe("with a mouse and a light bar", () => {
  test.use({ cartItems: ["Wireless Mouse", "Monitor Light Bar"] });

  test("express delivery adds $9.99 to the total", async ({ atCheckout: page }) => {
    await expect(page.getByTestId("order-total")).toHaveText("$78.50");

    await page.getByLabel("Express").check();

    await expect(page.getByTestId("order-total")).toHaveText("$88.49");
  });
});

test.describe("as Ana", () => {
  test.use({ user: "ana", cartItems: ["USB Microphone"] });

  test("the full name is prefilled with the signed-in user's name", async ({ atCheckout: page }) => {
    await expect(page.getByLabel("Full name")).toHaveValue("Ana");
  });
});

test("an empty cart sends you back to the cart page", async ({ atCheckout: page }) => {
  await expect(page).toHaveURL("/practice/cart");
  await expect(page.getByText("Your cart is empty.")).toBeVisible();
});
npx playwright test
Running 4 tests using 1 worker

  ✓  1 [chromium] › tests/checkout.spec.ts:14:3 › with a mouse in the cart › a signed-in user can buy a product and sees a confirmation (3.1s)
  ✓  2 [chromium] › tests/checkout.spec.ts:28:3 › with a mouse and a light bar › express delivery adds $9.99 to the total (1.8s)
  ✓  3 [chromium] › tests/checkout.spec.ts:40:3 › as Ana › the full name is prefilled with the signed-in user's name (1.8s)
  ✓  4 [chromium] › tests/checkout.spec.ts:45:1 › an empty cart sends you back to the cart page (989ms)

  4 passed (8.1s)
What’s happening
  1. user: ["rohit", { option: true }] declares an option fixture: a value with a default, marked as configurable. The tuple form [value, options] is how any fixture gets options (scope, auto, option, timeout, box, title).
  2. signedIn asks for the built-in page and the user option, signs in through the form, waits for "Signed in as …" (so the test never starts mid-sign-in), and calls use(page). atCheckout asks for signedIn (renaming it to page in the pattern), adds each product, waits for the cart count, and opens the checkout.
  3. Each describe sets the state it needs with test.use: one mouse; a mouse and a light bar ($29.50 + $49.00 = $78.50, then $88.49 with express); Ana with a microphone. The tests themselves are pure act and assert; there's no arrange code left in them.
  4. "as Ana" checks the prefilled name is "Ana": the user option flowed into signedIn, so the same fixture signs in as whoever the group says.
  5. The last test uses the defaults (rohit, empty cart): atCheckout waits for "Cart (0)", goes to the checkout, and the shop sends it back to the cart, which is the behaviour being tested.
  6. fillDetails stays a plain helper: it has no setup/teardown and isn't a starting state, just repeated lines. Not everything should be a fixture (see "Fixtures vs page objects vs helpers" below).
  7. All four tests passed in one worker, each with its own context. Compared with Chapter 3, the arrange code moved out of every test into one place, and changing how sign-in works (Chapter 8 replaces the form with a saved session) is now a change to one fixture.
AdvancedWorker-scoped fixtures: expensive things, once per worker

A worker-scoped fixture is set up once per worker and shared by all tests that worker runs. Use it for things that are slow to create and that tests only read: a test database seeded once, a server started once, a catalogue fetched once. It can only depend on other worker-scoped fixtures (browser, playwright, browserName), never on page or request, because those belong to a single test.

Here the catalogue is fetched from the shop's API once, and tests use it to check the UI against the data, instead of hard-coding product names:

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

export type Product = { id: string; name: string; category: string; price: number; stock: number };

export const test = base.extend<{}, { catalogue: Product[] }>({
  catalogue: [async ({ playwright }, use) => {
    console.log("catalogue: fetching once for this worker");
    const api = await playwright.request.newContext({ baseURL: "https://rohit-playwright.pages.dev" });
    const res = await api.get("/practice/api/products.json");
    await use(await res.json());
    await api.dispose();
  }, { scope: "worker" }],
});

export { expect } from "@playwright/test";
tests/catalogue.spec.ts
import { test, expect } from "../fixtures";

test.beforeEach(async ({ page }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
});

test("every sold-out product has a disabled Add to cart button", async ({ page, catalogue }) => {
  const soldOut = catalogue.filter((p) => p.stock === 0);
  expect(soldOut.length).toBeGreaterThan(0);
  for (const p of soldOut) {
    await expect(page.getByTestId(`product-${p.id}`).getByRole("button", { name: "Add to cart" })).toBeDisabled();
  }
});

test("sorting by price puts the cheapest product first", async ({ page, catalogue }) => {
  const cheapest = [...catalogue].sort((a, b) => a.price - b.price)[0];
  await page.getByLabel("Sort by").selectOption("Price: low to high");
  await expect(page.getByRole("listitem").first()).toContainText(cheapest.name);
});
npx playwright test
Running 2 tests using 1 worker

catalogue: fetching once for this worker
  ✓  1 [chromium] › tests/catalogue.spec.ts:10:1 › every sold-out product has a disabled Add to cart button (1.5s)
  ✓  2 [chromium] › tests/catalogue.spec.ts:18:1 › sorting by price puts the cheapest product first (1.7s)

  2 passed (3.6s)
What’s happening
  1. { scope: "worker" } makes catalogue a worker fixture. It depends on playwright (the worker-scoped Playwright object) and creates its own API context with playwright.request.newContext, because the test-scoped request fixture isn't available at worker scope.
  2. The base URL is written out in full: baseURL from the config is a test-scoped option fixture, and a worker fixture can't depend on a test-scoped one.
  3. "catalogue: fetching once for this worker" prints once, though both tests use the catalogue. With four workers it would print up to four times, once in each worker that runs a test needing it.
  4. The first test finds the sold-out products from the data (the Vertical Mouse, ms-02) and checks each one's button is disabled. Add another sold-out product to the JSON and the test checks it too, without an edit.
  5. The second test works out the cheapest product from the data ($29.50, the Wireless Mouse) and checks the sorted list starts with it.
  6. The trade-off: worker fixtures are shared, so a test that changes one (adds a product to a shared database) affects every later test in that worker. Keep them read-only, or give each worker its own copy keyed by testInfo.workerIndex / parallelIndex.
AdvancedAutomatic fixtures: something every test gets

An auto fixture ({ auto: true }) runs for every test without being asked for. It's the clean way to do what a global beforeEach/afterEach would, for every file that imports your test: collect logs, set a cookie banner's "dismissed" flag, or check something after every test. A popular one: fail any test whose page threw an uncaught error, even if its own assertions passed.

fixtures.ts
import { test as base, expect } from "@playwright/test";

export const test = base.extend<{ failOnPageErrors: void }>({
  failOnPageErrors: [async ({ page }, use) => {
    const errors: string[] = [];
    page.on("pageerror", (error) => errors.push(error.message));
    await use();
    expect(errors, "uncaught errors in the page").toEqual([]);
  }, { auto: true }],
});

export { expect };
tests/errors.spec.ts
import { test, expect } from "../fixtures";

test("the products page has no uncaught errors", async ({ page }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page.getByRole("listitem")).toHaveCount(8);
});

test("a page that throws fails the test", async ({ page }) => {
  // Simulate a bug: a script on every page throws after it loads.
  await page.addInitScript(() => {
    window.addEventListener("load", () => {
      throw new Error("reviews widget crashed");
    });
  });
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page.getByRole("listitem")).toHaveCount(8);
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/errors.spec.ts:3:1 › the products page has no uncaught errors (1.4s)
  ✘  2 [chromium] › tests/errors.spec.ts:11:1 › a page that throws fails the test (1.4s)


  1) [chromium] › tests/errors.spec.ts:11:1 › a page that throws fails the test ────────────────────

    Error: uncaught errors in the page

    expect(received).toEqual(expected) // deep equality

    - Expected  - 1
    + Received  + 4

    - Array []
    + Array [
    +   "reviews widget crashed",
    +   "reviews widget crashed",
    + ]

       at ../fixtures.ts:8

       6 |     page.on("pageerror", (error) => errors.push(error.message));
       7 |     await use();
    >  8 |     expect(errors, "uncaught errors in the page").toEqual([]);
         |                                                   ^
       9 |   }, { auto: true }],
      10 | });
      11 |
        at Object.exports.test._test.test.extend.failOnPageErrors.auto (<project>/fixtures.ts:8:51)

    Error Context: test-results/errors-a-page-that-throws-fails-the-test-chromium/error-context.md

  1 failed
    [chromium] › tests/errors.spec.ts:11:1 › a page that throws fails the test ─────────────────────
  1 passed (3.2s)
What’s happening
  1. failOnPageErrors is auto, so both tests get it without mentioning it. It listens for pageerror (an uncaught exception in the page's JavaScript) on the test's page, lets the test run, then asserts the list is empty in its teardown.
  2. The first test passes: the shop throws nothing.
  3. The second test injects a bug with addInitScript: a load listener that throws, on every page the test opens. Its own assertions all pass (sign-in works, eight products appear).
  4. The test still fails, deliberately, at the fixture's teardown: the error report shows the custom message "uncaught errors in the page" and the two "reviews widget crashed" messages, one for the sign-in page and one for the products page.
  5. That's the value of an auto fixture: a whole class of bug (a broken script that the visible flow survives) is caught by every test in the suite, written once. Add an allow-list for known third-party noise, or you'll be tempted to switch it off.
AdvancedOptions per project

Because user is an option, a project in the config can set it. Two projects run the same tests as two different users, with no change to the test files:

playwright.config.ts
import { defineConfig, devices } from "@playwright/test";
import type { Options } from "./fixtures";

export default defineConfig<Options>({
  testDir: "./tests",
  use: { baseURL: "https://rohit-playwright.pages.dev" },
  projects: [
    { name: "as-rohit", use: { ...devices["Desktop Chrome"], user: "rohit" } },
    { name: "as-ana", use: { ...devices["Desktop Chrome"], user: "ana" } },
  ],
});
fixtures.ts
import { test as base, expect } from "@playwright/test";

export type Options = { user: string };

export const test = base.extend<Options>({
  user: ["rohit", { option: true }],
});

export { expect };
tests/header.spec.ts
import { test, expect } from "../fixtures";

test("the header shows who is signed in", async ({ page, user }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill(user);
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page.getByText(`Signed in as ${user}`)).toBeVisible();
});
npx playwright test
Running 2 tests using 2 workers

  ✓  2 [as-rohit] › tests/header.spec.ts:3:1 › the header shows who is signed in (988ms)
  ✓  1 [as-ana] › tests/header.spec.ts:3:1 › the header shows who is signed in (987ms)

  2 passed (1.4s)
What’s happening
  1. defineConfig<Options> tells TypeScript about the custom option, so user: "ana" in a project's use type-checks. The config imports only the type from fixtures.ts.
  2. Each project sets user, and the option fixture picks up the project's value instead of its default. One test × two projects = two runs, each line prefixed by its project name.
  3. This is how teams run one suite against several roles, locales or tenants: the variation lives in the config, and the tests stay the same.

#The Page Object Model

Added

A page object is a class that represents one page (or one component) of your app, from a user's point of view. It holds the locators for that page and methods named for what a user does there: signIn(user), add("Wireless Mouse"), increase("Wireless Mouse"), placeOrder(). Tests then read as a series of user actions, and when the page's markup changes, you fix one class instead of forty tests.

The mental model: a page object is the page's API for tests. The test says what to do ("sign in as rohit"); the page object knows how on this particular page (which fields, which button). It's the same separation you'd want in production code: callers don't reach into the internals.

What goes in a page object, and what stays in the test:

In the page objectIn the test
Locators, defined once (this.total = page.getByTestId("cart-total"))The scenario: which user, which products, what order
Actions in user words (signIn, add, placeOrder)Assertions about the outcome the test is about
Navigation that returns the next page object (openCart() → CartPage)Test data
Small waits that are part of an action ("sign-in finished")Anything that makes the test's purpose clear when read

Here are page objects for the four main pages of the shop, as files of a suite, and tests that use them:

pages/login-page.ts
import { expect, type Locator, type Page } from "@playwright/test";
import { ShopPage } from "./shop-page";

export class LoginPage {
  readonly username: Locator;
  readonly password: Locator;
  readonly signInButton: Locator;
  readonly error: Locator;

  constructor(private readonly page: Page) {
    this.username = page.getByLabel("Username");
    this.password = page.getByLabel("Password");
    this.signInButton = page.getByRole("button", { name: "Sign in" });
    this.error = page.getByRole("alert");
  }

  async goto() {
    await this.page.goto("/practice/");
  }

  async signInAs(user: string, password = "playwright") {
    await this.username.fill(user);
    await this.password.fill(password);
    await this.signInButton.click();
  }

  // The happy path: sign in and land on the products page.
  async signIn(user: string): Promise<ShopPage> {
    await this.signInAs(user);
    const shop = new ShopPage(this.page);
    await expect(shop.heading).toBeVisible();
    return shop;
  }
}
pages/shop-page.ts
import type { Locator, Page } from "@playwright/test";
import { CartPage } from "./cart-page";

export class ShopPage {
  readonly heading: Locator;
  readonly search: Locator;
  readonly products: Locator;
  readonly cartLink: Locator;

  constructor(private readonly page: Page) {
    this.heading = page.getByRole("heading", { name: "Products" });
    this.search = page.getByLabel("Search products");
    this.products = page.getByRole("list", { name: "Products" }).getByRole("listitem");
    this.cartLink = page.getByRole("link", { name: /^Cart \(\d+\)$/ });
  }

  product(name: string): Locator {
    return this.products.filter({ hasText: name });
  }

  async add(...names: string[]) {
    for (const name of names) await this.product(name).getByRole("button", { name: "Add to cart" }).click();
  }

  async openCart(): Promise<CartPage> {
    await this.cartLink.click();
    return new CartPage(this.page);
  }
}
pages/cart-page.ts
import type { Locator, Page } from "@playwright/test";
import { CheckoutPage } from "./checkout-page";

export class CartPage {
  readonly total: Locator;
  readonly empty: Locator;

  constructor(private readonly page: Page) {
    this.total = page.getByTestId("cart-total");
    this.empty = page.getByText("Your cart is empty.");
  }

  row(name: string): Locator {
    return this.page.getByRole("row", { name: new RegExp(name) });
  }

  quantity(name: string): Locator {
    return this.page.getByLabel(`Quantity of ${name}`, { exact: true });
  }

  async increase(name: string) {
    await this.page.getByRole("button", { name: `Increase quantity of ${name}` }).click();
  }

  async remove(name: string) {
    await this.page.getByRole("button", { name: `Remove ${name}` }).click();
  }

  async checkout(): Promise<CheckoutPage> {
    await this.page.getByRole("link", { name: "Checkout" }).click();
    return new CheckoutPage(this.page);
  }
}
pages/checkout-page.ts
import type { Locator, Page } from "@playwright/test";

export type Details = { email: string; address: string; express?: boolean };

export class CheckoutPage {
  readonly fullName: Locator;
  readonly total: Locator;
  readonly formError: Locator;
  readonly confirmation: Locator;

  constructor(private readonly page: Page) {
    this.fullName = page.getByLabel("Full name");
    this.total = page.getByTestId("order-total");
    this.formError = page.getByRole("alert");
    this.confirmation = page.getByRole("heading", { level: 1 });
  }

  async fillDetails({ email, address, express = false }: Details) {
    await this.page.getByLabel("Email").fill(email);
    await this.page.getByLabel("Delivery address").fill(address);
    if (express) await this.page.getByLabel("Express").check();
    await this.page.getByLabel("I agree to the terms").check();
  }

  async placeOrder() {
    await this.page.getByRole("button", { name: "Place order" }).click();
  }
}
tests/shopping.spec.ts
import { test, expect } from "@playwright/test";
import { LoginPage } from "../pages/login-page";

test("a customer buys two products with express delivery", async ({ page }) => {
  const login = new LoginPage(page);
  await login.goto();
  const shop = await login.signIn("rohit");

  await shop.add("Wireless Mouse", "Monitor Light Bar");
  const cart = await shop.openCart();
  await expect(cart.total).toHaveText("$78.50");

  const checkout = await cart.checkout();
  await checkout.fillDetails({ email: "rohit@example.com", address: "12 Long Street, Toronto", express: true });
  await expect(checkout.total).toHaveText("$88.49");
  await checkout.placeOrder();

  await expect(checkout.confirmation).toHaveText("Thank you, Rohit!");
  await expect(page.getByText("Total paid on delivery: $88.49")).toBeVisible();
});

test("increasing the quantity doubles the subtotal", async ({ page }) => {
  const login = new LoginPage(page);
  await login.goto();
  const shop = await login.signIn("ana");
  await shop.add("USB Microphone");
  const cart = await shop.openCart();

  await cart.increase("USB Microphone");

  await expect(cart.quantity("USB Microphone")).toHaveText("2");
  await expect(cart.total).toHaveText("$149.98");
});

test("a wrong password shows an error and stays on the sign-in page", async ({ page }) => {
  const login = new LoginPage(page);
  await login.goto();

  await login.signInAs("rohit", "not-the-password");

  await expect(login.error).toHaveText("Wrong username or password.");
  await expect(page).toHaveURL("/practice/");
});
npx playwright test tests/shopping.spec.ts
Running 3 tests using 1 worker

  ✓  1 [chromium] › tests/shopping.spec.ts:4:1 › a customer buys two products with express delivery (3.3s)
  ✓  2 [chromium] › tests/shopping.spec.ts:22:1 › increasing the quantity doubles the subtotal (1.8s)
  ✓  3 [chromium] › tests/shopping.spec.ts:35:1 › a wrong password shows an error and stays on the sign-in page (951ms)

  3 passed (6.6s)
What’s happening
  1. Each class takes the page in its constructor and defines its locators once, as fields. Locators are lazy recipes (Chapter 4), so creating them in the constructor costs nothing and finds nothing yet; they resolve fresh each time an action or assertion uses them.
  2. Methods are named for user intentions: signIn("rohit"), add(...), increase(...), fillDetails({...}), placeOrder(). The first test reads like the journey it covers: sign in, add two products, open the cart, check out with express, see the thank-you.
  3. Navigation methods return the next page object: signIn returns a ShopPage (after waiting for its heading, so the caller never acts mid-sign-in), openCart returns a CartPage, checkout returns a CheckoutPage. The types guide you through the journey.
  4. LoginPage has two sign-in methods on purpose: signIn(user) is the happy path that must land on the shop, and signInAs(user, password) just submits the form, for tests about failure, like the third test, where landing on the shop would be wrong.
  5. The assertions stay in the tests: the totals ($78.50, $88.49, $149.98 for two microphones at $74.99), the thank-you heading, the error text. The page objects expose locators (cart.total, login.error) for the tests to assert on. A test's purpose is in its assertions, so hiding them in methods would hide the purpose.
  6. If the shop renamed "Delivery address" to "Shipping address", one line in CheckoutPage changes and every test keeps working. That's the payoff, and it grows with the number of tests.
AdvancedPage objects that go wrong

#Fixtures vs page objects vs helpers

Added

Three tools, and the most common framework-design interview question is how they fit together. They answer different questions:

ToolAnswersHas setup/teardown?Example
Fixture"What state does this test start in, and who cleans up?"yes, around usea signed-in page, a seeded user, a worker's database
Page object"How do I do things on this page?"nocart.increase("Mouse"), login.signIn("rohit")
Helper function"How do I compute or repeat this small thing?"nomoney(29.5), uniqueEmail(testInfo)

The mental model: a fixture is the stage crew, a page object is the script for one scene, a helper is a prop. The crew sets the stage before the scene and clears it after; the script says what the actor does; props are small things used along the way. They combine naturally: fixtures create page objects (already signed in, already on the right page) and hand them to the test, so tests ask for ({ cart }) and start acting.

Here the page objects from the previous topic are joined by a fixture file and a helper. The tests ask for page objects in the state they need:

fixtures.ts
import { test as base, expect, type TestInfo } from "@playwright/test";
import { LoginPage } from "./pages/login-page";
import { ShopPage } from "./pages/shop-page";
import { CartPage } from "./pages/cart-page";

type Fixtures = { loginPage: LoginPage; shop: ShopPage; cart: CartPage };
type Options = { user: string; cartItems: string[] };

export const test = base.extend<Options & Fixtures>({
  user: ["rohit", { option: true }],
  cartItems: [["Wireless Mouse"], { option: true }],

  loginPage: async ({ page }, use) => {
    const login = new LoginPage(page);
    await login.goto();
    await use(login);
  },
  shop: async ({ loginPage, user }, use) => {
    await use(await loginPage.signIn(user));
  },
  cart: async ({ shop, cartItems }, use) => {
    await shop.add(...cartItems);
    await use(await shop.openCart());
  },
});

// Helpers: plain functions, no state.
export const money = (n: number) => `$${n.toFixed(2)}`;
export const uniqueEmail = (testInfo: TestInfo) => `rohit+${testInfo.workerIndex}-${testInfo.repeatEachIndex}-${Date.now()}@example.com`;

export { expect };
tests/with-fixtures.spec.ts
import { test, expect, money, uniqueEmail } from "../fixtures";

test("removing the only item empties the cart", async ({ cart }) => {
  await cart.remove("Wireless Mouse");
  await expect(cart.empty).toBeVisible();
});

test.describe("two microphones", () => {
  test.use({ user: "ana", cartItems: ["USB Microphone", "USB Microphone"] });

  test("the cart totals both", async ({ cart }) => {
    await expect(cart.quantity("USB Microphone")).toHaveText("2");
    await expect(cart.total).toHaveText(money(74.99 * 2));
  });
});

test("an order can be placed from the cart", async ({ cart, page }, testInfo) => {
  const checkout = await cart.checkout();
  await checkout.fillDetails({ email: uniqueEmail(testInfo), address: "12 Long Street, Toronto" });
  await checkout.placeOrder();
  await expect(checkout.confirmation).toHaveText("Thank you, Rohit!");
  await expect(page.getByText(`Total paid on delivery: ${money(29.5)}`)).toBeVisible();
});

test("the sign-in page rejects the locked account", async ({ loginPage }) => {
  await loginPage.signInAs("locked");
  await expect(loginPage.error).toHaveText("This account is locked. Contact support.");
});
npx playwright test tests/with-fixtures.spec.ts
Running 4 tests using 1 worker

  ✓  1 [chromium] › tests/with-fixtures.spec.ts:3:1 › removing the only item empties the cart (1.9s)
  ✓  2 [chromium] › tests/with-fixtures.spec.ts:11:3 › two microphones › the cart totals both (1.8s)
  ✓  3 [chromium] › tests/with-fixtures.spec.ts:17:1 › an order can be placed from the cart (3.2s)
  ✓  4 [chromium] › tests/with-fixtures.spec.ts:25:1 › the sign-in page rejects the locked account (896ms)

  4 passed (8.3s)
What’s happening
  1. Three fixtures form a chain: loginPage (a LoginPage on the sign-in page) → shop (signed in as user, a ShopPage) → cart (cartItems added, a CartPage). Each one builds on a page object method, so the "how" lives in the page objects and the "which state" lives in the fixtures.
  2. The first test asks for cart and gets a signed-in rohit with one Wireless Mouse (the default cartItems), already on the cart page. Its body is one action and one assertion.
  3. "two microphones" changes both options with test.use; adding the same product twice gives a quantity of 2, and the helper money(74.99 * 2) formats the expected total as "$149.98".
  4. The third test asks for cart and page (the same page the page objects drive) plus testInfo, and uses the uniqueEmail helper to make an address no other test or run will use. On a real backend, that's what stops parallel tests colliding.
  5. The last test asks only for loginPage, so it's not signed in: fixtures are lazy, and shop and cart never run for this test. It checks the locked account's message.
  6. The split that makes this maintainable: tests say what state they need and what they check; fixtures build state and clean up; page objects know the pages; helpers are tiny pure functions. Each has one reason to change.
AdvancedYou don't have to use page objects

#Test data and isolation

Added

Chapter 3 set the rule: every test must be able to run alone, in any order, at the same time as any other. Fixtures are how you keep it in a real suite. Each test gets its data from a fixture that creates it fresh (unique per test), and the fixture's teardown cleans it up, even when the test fails.

The mental model: every test brings its own sandbox and takes it home. It doesn't play in another test's sandbox, it doesn't expect one to be left out for it, and if it trips and falls (fails), the sandbox still gets packed away.

In the Practice Shop, the browser context already gives each test a private sandbox (localStorage is per context). Here are four tests that each place an order, all at once in four workers, with --repeat-each=2 to run each twice:

playwright.config.ts
import { defineConfig, devices } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  fullyParallel: true,
  workers: 4,
  use: { baseURL: "https://rohit-playwright.pages.dev" },
  projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
});
tests/orders.spec.ts
import { test, expect } from "@playwright/test";

for (const product of ["Wireless Mouse", "Compact Keyboard", "USB Microphone", "Standing Desk Mat"]) {
  test(`order a ${product}`, async ({ page }, testInfo) => {
    await page.goto("/practice/");
    await page.getByLabel("Username").fill("rohit");
    await page.getByLabel("Password").fill("playwright");
    await page.getByRole("button", { name: "Sign in" }).click();
    await page.getByRole("listitem").filter({ hasText: product }).getByRole("button", { name: "Add to cart" }).click();
    await page.getByRole("link", { name: "Cart (1)" }).click();
    await page.getByRole("link", { name: "Checkout" }).click();
    await page.getByLabel("Email").fill(`rohit+${testInfo.parallelIndex}@example.com`);
    await page.getByLabel("Delivery address").fill("12 Long Street, Toronto");
    await page.getByLabel("I agree to the terms").check();
    await page.getByRole("button", { name: "Place order" }).click();

    await expect(page.getByText("Your order ORD-1001 is confirmed.")).toBeVisible();
  });
}
npx playwright test --repeat-each=2
Running 8 tests using 4 workers

  ✓  1 [chromium] › tests/orders.spec.ts:4:3 › order a Standing Desk Mat (3.1s)
  ✓  4 [chromium] › tests/orders.spec.ts:4:3 › order a USB Microphone (3.1s)
  ✓  3 [chromium] › tests/orders.spec.ts:4:3 › order a Compact Keyboard (3.1s)
  ✓  2 [chromium] › tests/orders.spec.ts:4:3 › order a Wireless Mouse (3.1s)
  ✓  8 [chromium] › tests/orders.spec.ts:4:3 › order a Wireless Mouse (3.1s)
  ✓  7 [chromium] › tests/orders.spec.ts:4:3 › order a USB Microphone (3.1s)
  ✓  5 [chromium] › tests/orders.spec.ts:4:3 › order a Compact Keyboard (3.1s)
  ✓  6 [chromium] › tests/orders.spec.ts:4:3 › order a Standing Desk Mat (3.1s)

  8 passed (7.2s)
What’s happening
  1. fullyParallel: true with workers: 4 lets every test run in any worker at the same time; --repeat-each=2 runs each of the four tests twice, so eight orders are placed with up to four running at once.
  2. Every one of them gets ORD-1001. The shop's order counter lives in localStorage, and each test has its own context, so no test sees another's orders. If the counter were shared (a real database with one sequence), asserting an exact order number would be the classic parallel-flaky test.
  3. testInfo.parallelIndex is the worker's slot (0 to 3 here), stable for the worker's life; it's used to give each worker a different email address. On a real backend, use it for per-worker accounts (Chapter 8), and add a timestamp or random id for per-test data.
  4. Because each test arranges everything itself, the result doesn't depend on which worker ran what, or in which order. That's what lets a suite scale from 1 worker to 40, and across machines (Chapter 12).
AdvancedCleanup that runs even when the test fails

On a real backend, data a test creates outlives the test: users, orders, uploaded files. Create it in a fixture and delete it in the fixture's teardown, so it's removed even when the test fails halfway. Here a tiny API stands in for your backend (it starts with the tests through webServer), and one test is marked test.fail(): it's expected to fail, and Playwright reports it as passing only if it does fail. The fixture prints what it creates and deletes:

api.mjs
import { createServer } from "node:http";

const users = new Map();
let next = 1;
createServer(async (req, res) => {
  const send = (status, body) => res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
  const [, , id] = req.url.split("/"); // /users/:id
  if (req.method === "POST" && req.url === "/users") {
    let raw = "";
    for await (const chunk of req) raw += chunk;
    const user = { id: String(next++), ...JSON.parse(raw) };
    users.set(user.id, user);
    return send(201, user);
  }
  if (req.method === "GET" && req.url === "/users") return send(200, [...users.values()]);
  if (req.method === "DELETE" && users.delete(id)) return send(204, {});
  send(404, { error: "not found" });
}).listen(4211, "127.0.0.1");
playwright.config.ts
import { defineConfig } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  workers: 1,
  use: { baseURL: "http://127.0.0.1:4211" },
  webServer: { command: "node api.mjs", url: "http://127.0.0.1:4211/users" },
});
fixtures.ts
import { test as base, expect } from "@playwright/test";

type User = { id: string; name: string; email: string };

export const test = base.extend<{ newUser: User }>({
  newUser: async ({ request }, use, testInfo) => {
    const email = `user-${testInfo.testId}-${testInfo.retry}@example.com`;
    const created = await request.post("/users", { data: { name: "Test User", email } });
    expect(created.status()).toBe(201);
    const user: User = await created.json();
    console.log(`created user ${user.id} for "${testInfo.title}"`);

    await use(user);

    const deleted = await request.delete(`/users/${user.id}`);
    console.log(`deleted user ${user.id} (status ${deleted.status()})`);
  },
});

export { expect };
tests/users.spec.ts
import { test, expect } from "../fixtures";

test("a new user is listed", async ({ request, newUser }) => {
  const users = await (await request.get("/users")).json();
  expect(users.map((u: { id: string }) => u.id)).toContain(newUser.id);
});

test("a failing test still cleans up", async ({ newUser }) => {
  test.fail(); // expected to fail: the assertion below is wrong on purpose
  expect(newUser.name).toBe("Someone Else");
});

test("nothing is left behind", async ({ request }) => {
  expect(await (await request.get("/users")).json()).toEqual([]);
});
npx playwright test
Running 3 tests using 1 worker

created user 1 for "a new user is listed"
deleted user 1 (status 204)
  ✓  1 tests/users.spec.ts:3:1 › a new user is listed (40ms)
created user 2 for "a failing test still cleans up"
deleted user 2 (status 204)
  ✘  2 tests/users.spec.ts:8:1 › a failing test still cleans up (8ms)
  ✓  3 tests/users.spec.ts:13:1 › nothing is left behind (4ms)

  3 passed (475ms)
What’s happening
  1. webServer starts api.mjs, a 20-line in-memory users API on port 4211 (this chapter's own port), and the tests use it through the request fixture. Your real API would take its place.
  2. newUser creates a user with POST /users before the test, using testInfo.testId and retry to make the email unique per test and per retry, and deletes it with DELETE /users/:id after use.
  3. The first test sees its user in the list. The fixture then deletes it (status 204).
  4. The second test fails, as test.fail() says it should. The list reporter still marks it ✘ (it did fail), but because the failure was expected it counts as a pass: the summary says 3 passed. Its fixture teardown still ran: the output shows user 2 deleted too. With cleanup in an afterEach that looked up a variable, a crash before the variable was set would skip it; with a fixture, cleanup is tied to the thing that was created.
  5. The third test lists all users and finds none: everything the earlier tests made was removed.
  6. Don't depend on cleanup, though: a killed CI job never runs teardown. Unique names mean leftovers never collide with the next run, and a nightly job can sweep anything older than a day.

#Your turn: fixtures and page objects for the account page

Added
Your turn: an AccountPage page object

Write an AccountPage page object for /practice/account with the "Display name" field, a saveDisplayName(name) method and a message locator for the status text. Use it in a test that signs in as ana, saves "Ana P." and checks the message "Saved. You’ll appear as “Ana P.”." Then reload and check the field still shows "Ana P.".

Show answer
pages/account-page.ts
import type { Locator, Page } from "@playwright/test";

export class AccountPage {
  readonly displayName: Locator;
  readonly message: Locator;

  constructor(private readonly page: Page) {
    this.displayName = page.getByLabel("Display name");
    this.message = page.getByRole("status").filter({ hasText: "Saved" });
  }

  async goto() {
    await this.page.goto("/practice/account");
  }

  async saveDisplayName(name: string) {
    await this.displayName.fill(name);
    await this.page.getByRole("button", { name: "Save" }).click();
  }
}
tests/account.spec.ts
import { test, expect } from "@playwright/test";
import { AccountPage } from "../pages/account-page";

test("a saved display name is shown and kept after a reload", async ({ page }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("ana");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page.getByText("Signed in as ana")).toBeVisible();

  const account = new AccountPage(page);
  await account.goto();
  await expect(account.displayName).toHaveValue("Ana");

  await account.saveDisplayName("Ana P.");

  await expect(account.message).toHaveText("Saved. You’ll appear as “Ana P.”.");
  await page.reload();
  await expect(account.displayName).toHaveValue("Ana P.");
});
npx playwright test
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/account.spec.ts:4:1 › a saved display name is shown and kept after a reload (1.1s)

  1 passed (1.6s)
What’s happening
  1. The page object holds two locators and two actions, all in user terms. message is narrowed with filter({ hasText: "Saved" }) because the account page has several role="status" elements (the avatar message, the danger-zone message, the newsletter one inside its shadow root), and an unfiltered getByRole("status") would match more than one and fail strict mode.
  2. The test waits for "Signed in as ana" before going to the account page. Without it, goto could run before the sign-in finished, and the account page would redirect to sign-in.
  3. Before saving, the field shows "Ana" (the shop's default display name is the user's name), which proves the starting state.
  4. After saving, the message uses the shop's curly quotes and apostrophe exactly (You’ll, “Ana P.”), so the expected string must too; a straight ' wouldn't match.
  5. After page.reload(), the field still says "Ana P.", because the shop saved it in localStorage. The assertions stay in the test; the page object only knows how to use the page.
Your turn: a signedInAs fixture with an option

Turn the sign-in into a fixture: an option user (default "rohit") and a fixture account that signs in as user and hands the test an AccountPage already open. Write two tests: one with the default user checking the field shows "Rohit", and one in a describe with test.use({ user: "ana" }) checking it shows "Ana".

Show answer
pages/account-page.ts
import type { Locator, Page } from "@playwright/test";

export class AccountPage {
  readonly displayName: Locator;

  constructor(private readonly page: Page) {
    this.displayName = page.getByLabel("Display name");
  }

  async goto() {
    await this.page.goto("/practice/account");
  }
}
fixtures.ts
import { test as base, expect } from "@playwright/test";
import { AccountPage } from "./pages/account-page";

export const test = base.extend<{ user: string; account: AccountPage }>({
  user: ["rohit", { option: true }],
  account: async ({ page, user }, use) => {
    await page.goto("/practice/");
    await page.getByLabel("Username").fill(user);
    await page.getByLabel("Password").fill("playwright");
    await page.getByRole("button", { name: "Sign in" }).click();
    await expect(page.getByText(`Signed in as ${user}`)).toBeVisible();
    const account = new AccountPage(page);
    await account.goto();
    await use(account);
  },
});

export { expect };
tests/account.spec.ts
import { test, expect } from "../fixtures";

test("the display name defaults to the user's name", async ({ account }) => {
  await expect(account.displayName).toHaveValue("Rohit");
});

test.describe("as Ana", () => {
  test.use({ user: "ana" });

  test("Ana's display name defaults to Ana", async ({ account }) => {
    await expect(account.displayName).toHaveValue("Ana");
  });
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/account.spec.ts:3:1 › the display name defaults to the user's name (1.0s)
  ✓  2 [chromium] › tests/account.spec.ts:10:3 › as Ana › Ana's display name defaults to Ana (992ms)

  2 passed (2.5s)
What’s happening
  1. user: ["rohit", { option: true }] is the option; account depends on page and user, signs in, waits for the header, opens the account page and hands over the page object.
  2. The first test uses the default, so it's signed in as rohit and the field shows "Rohit".
  3. The describe overrides the option with test.use({ user: "ana" }); the same fixture now signs in as ana, and the field shows "Ana".
  4. Neither test has any arrange code: each asks for account and asserts. Adding a third user is a three-line describe, not a copy of the sign-in steps.

Written fresh, no doc. Tests were run with @playwright/test 1.65.1 (Chrome for Testing 159, Firefox 159, WebKit 27.2) against the Practice Shop at /practice/; facts come from playwright.dev, read 2026-11-24.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.