Playwright NotesRohit’s interview study guide
Chapter 11

Debugging and Flaky Tests

How to find out why a test failed (the error message, the error context, traces, the debugging tools), what really makes tests flaky, how retries report a flaky test and how to keep flakes from rotting a suite, and how to take control of time with the clock API. Every test was run with Playwright 1.65.1 against the Practice Shop.

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

#The Trace Viewer

Added

A test that fails on your laptop is easy: run it again with the browser open and watch. A test that failed on CI, once, an hour ago is the hard case, and it's the normal case. You can't watch it any more. What you need is a recording of everything that happened, detailed enough to answer "what did the page look like when the click happened?" without running anything again.

That's a trace: a trace.zip that Playwright writes while a test runs, holding every action with its timing, a DOM snapshot before, during and after each action (real HTML you can inspect, not a picture), a screencast, every network request and response, console messages, errors and the test's source. The Trace Viewer opens it as an interactive timeline.

The mental model: an aeroplane's flight recorder. You don't watch it during a normal flight; it costs little to keep running; and when something goes wrong, it's the only witness. So the usual setting records traces only when something goes wrong: trace: "on-first-retry" (record when a failed test is retried) or trace: "retain-on-failure" (record every test, keep the trace only if it failed).

Here a test fails, and the trace explains why. The test author believed the Wireless Mouse was the first product:

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

export default defineConfig({
  testDir: "./tests",
  use: {
    baseURL: "https://rohit-playwright.pages.dev",
    trace: "retain-on-failure", // record every test, keep the trace only when it fails
  },
  projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
});
tests/toast.spec.ts
import { test, expect, type Page } from "@playwright/test";

async function signIn(page: 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("signing in shows the products", async ({ page }) => {
  await signIn(page);
  await expect(page.getByRole("listitem")).toHaveCount(8);
});

test("adding the mouse names it in the message", async ({ page }) => {
  await signIn(page);
  await page.getByRole("button", { name: "Add to cart" }).first().click(); // "the mouse is first" (it isn't)
  await expect(page.getByRole("status").filter({ hasText: "Added" })).toHaveText("Added Wireless Mouse to your cart", { timeout: 2000 });
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/toast.spec.ts:10:1 › signing in shows the products (1.5s)
  ✘  2 [chromium] › tests/toast.spec.ts:15:1 › adding the mouse names it in the message (3.5s)


  1) [chromium] › tests/toast.spec.ts:15:1 › adding the mouse names it in the message ──────────────

    Error: expect(locator).toHaveText(expected) failed

    Locator:  getByRole('status').filter({ hasText: 'Added' })
    Expected: "Added Wireless Mouse to your cart"
    Received: "Added Mechanical Keyboard to your cart"
    Timeout:  2000ms

    Call log:
      - Expect "toHaveText" getByRole('status').filter({ hasText: 'Added' }) with timeout 2000ms
      - waiting for getByRole('status').filter({ hasText: 'Added' })
        21 × locator resolved to <div class="toast" role="status" data-toast="">Added Mechanical Keyboard to your cart</div>
           - unexpected value "Added Mechanical Keyboard to your cart"


      16 |   await signIn(page);
      17 |   await page.getByRole("button", { name: "Add to cart" }).first().click(); // "the mouse is first" (it isn't)
    > 18 |   await expect(page.getByRole("status").filter({ hasText: "Added" })).toHaveText("Added Wireless Mouse to your cart", { timeout: 2000 });
         |                                                                       ^
      19 | });
      20 |
        at <project>/tests/toast.spec.ts:18:71

    Error Context: test-results/toast-adding-the-mouse-names-it-in-the-message-chromium/error-context.md

    attachment #2: trace (application/zip) ─────────────────────────────────────────────────────────
    test-results/toast-adding-the-mouse-names-it-in-the-message-chromium/trace.zip
    Usage:

        npx playwright show-trace test-results/toast-adding-the-mouse-names-it-in-the-message-chromium/trace.zip

    ────────────────────────────────────────────────────────────────────────────────────────────────

  1 failed
    [chromium] › tests/toast.spec.ts:15:1 › adding the mouse names it in the message ───────────────
  1 passed (5.5s)
list-files.mjs
// Prints every file under the given folders, sorted, so the page can show what a run really wrote.
import { readdirSync } from "node:fs";
import { join } from "node:path";
const walk = (d) => readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(join(d, e.name)) : [join(d, e.name)]));
for (const dir of process.argv.slice(2)) for (const f of walk(dir).sort()) console.log(f);
node list-files.mjs test-results
test-results/.last-run.json
test-results/toast-adding-the-mouse-names-it-in-the-message-chromium/error-context.md
test-results/toast-adding-the-mouse-names-it-in-the-message-chromium/trace.zip
What’s happening
  1. Both tests ran with tracing on. The passing test's trace was thrown away when it passed (that's what retain-on-failure means), so test-results/ holds a folder only for the failing test: its trace.zip and an error-context.md.
  2. The failure itself is already informative: the message said "Added Mechanical Keyboard to your cart", not the mouse. The output also prints the exact command to open the recording: npx playwright show-trace test-results/…/trace.zip.
  3. In the Trace Viewer (a window, so it wasn't run for this page; this is from the docs) you'd click the Click action in the list on the left and see three DOM snapshots: Before, Action (marking the point where the click landed) and After. The click point is on the first card, the Mechanical Keyboard. The bug is in the test, not the shop: .first() assumed an order nobody promised.
  4. The fix is a locator that says what the test means: page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }) (Chapter 4). The trace didn't just say that the test failed; it showed what the test actually did, which is the question you can't answer from the error alone.
AdvancedReading a trace from the terminal (1.59+)

Since 1.59, npx playwright trace reads a trace from the command line: trace open <file>, then actions, action <id>, requests, console, errors, snapshot, screenshot, attachments, and close. The release notes say it was added so coding agents can inspect failing tests, but it's just as handy over SSH or in a CI log. This little script runs it on the failing test's trace and hides the timings, which change every run:

read-trace.mjs
// Reads a trace with `npx playwright trace` and prints the action list and the errors, with timings hidden.
import { execFileSync } from "node:child_process";
const trace = (...args) => execFileSync("npx", ["playwright", "trace", ...args], { encoding: "utf8" });
const hideTimes = (s) => s.replace(/\d+:\d\d\.\d{3}/g, "…").replace(/\b\d+(\.\d+)?m?s\b/g, "…");

const summary = trace("open", process.argv[2]);
console.log(summary.split("\n").filter((l) => !/Duration|Start time/.test(l)).join("\n"));
console.log(hideTimes(trace("actions")));
console.log(trace("errors"));
trace("close");
node read-trace.mjs test-results/toast-adding-the-mouse-names-it-in-the-message-chromium/trace.zip
  Browser:      unknown
  Platform:     darwin
  Playwright:   1.65.1
  Title:        toast.spec.ts:15 › adding the mouse names it in the message
  Viewport:     default
  Actions:      26
  Pages:        1
  Network:      7 requests
  Errors:       1
  Attachments:  1
  Console:      0 messages


     # Time       Action                                                  Duration
  ──── ─────────  ─────────────────────────────────────────────────────── ────────
    1. …  Before Hooks                                                …
    2. …    Fixture "context"                                          …
    3. …      Create context                                           …
    4. …    Fixture "page"                                            …
    5. …      Create page                                             …
    6. …  Navigate                                                    …
                 /practice/
    7. …  Fill "rohit"                                                …
                 getByLabel('Username')
    8. …  Fill "playwright"                                           …
                 getByLabel('Password')
    9. …  Click                                                       …
                 getByRole('button', { name: 'Sign in' })
   10. …  Click                                                       …
                 getByRole('button', { name: 'Add to cart' }).first()
   11. …  Expect "toHaveText"                                         …  ✗
                 getByRole('status').filter({ hasText: 'Added' })
   12. …  After Hooks                                                 …
   13. …    Fixture "page"                                             …
   14. …    Fixture "context"                                         …
   15. …      Close context                                            …
   16. …  Attach "error-context"                                       …
   17. …  Worker Cleanup                                              …
   18. …    Fixture "browser"                                         …


  ✗ Error
    at toast.spec.ts:18:71

    Error: expect(locator).toHaveText(expected) failed
    
    Locator:  getByRole('status').filter({ hasText: 'Added' })
    Expected: "Added Wireless Mouse to your cart"
    Received: "Added Mechanical Keyboard to your cart"
    Timeout:  2000ms
    
    Call log:
      - Expect "toHaveText" getByRole('status').filter({ hasText: 'Added' }) with timeout 2000ms
      - waiting for getByRole('status').filter({ hasText: 'Added' })
        21 × locator resolved to <div class="toast" role="status" data-toast="">Added Mechanical Keyboard to your cart</div>
           - unexpected value "Added Mechanical Keyboard to your cart"
What’s happening
  1. trace open unpacks the zip and prints a summary: the Playwright version, the test's title, how many actions, network requests and errors were recorded. (The "Browser: unknown" line is what 1.65.1 really printed for this trace.)
  2. trace actions lists every step in order, including the fixtures Playwright set up (context, page) and tore down. Each Playwright call is one line with its locator: the Click on getByRole('button', { name: 'Add to cart' }).first(), then the Expect "toHaveText" marked ✗.
  3. trace errors prints the failing assertion, with its location in the source and its call log: expected "Added Wireless Mouse to your cart", received the keyboard message.
  4. From here you could run npx playwright trace snapshot <action-id> to inspect the DOM at that step, or trace requests to see the network. The GUI is nicer for humans; the CLI is what you'd script, or hand to an AI agent (Chapter 13).
AdvancedWhich trace setting to use

The values, from the 1.65 CLI help and the option's documentation in the installed types:

trace:RecordsUse it for
"off"nothingthe default
"on"every testdebugging locally; too heavy for a whole CI suite
"retain-on-failure"every run, keeps the runs that failed (even when a later retry passes)CI, with or without retries
"on-first-retry"the first retry of a failed testCI with retries (the generator's default)
"on-all-retries"every retrychasing a flake that fails several times
"retain-on-first-failure"only the first run of each test (not retries), kept if it failedCI with retries, when the first failure is the one you want
"retain-on-failure-and-retries" (1.59+)every run, keeps failed runs and every retrycomparing a failing attempt with the passing retry of a flaky test

Where to open a trace: npx playwright show-trace path/to/trace.zip (a local window), the HTML report (each failed test has a trace link), or trace.playwright.dev, which loads the file entirely in your browser (the docs say no data is sent anywhere). Traces contain everything the page showed and sent, including tokens and personal data in requests, so treat CI trace artifacts as sensitive.

#Debugging a failing test

Added

Most failures can be understood without running anything again, if you read the failure properly. A Playwright error has a fixed shape: what failed (the assertion or action and its locator), expected vs received, the timeout that ran out, a call log of what Playwright did while it waited, the source line with a caret, and a pointer to an error context file. The call log is the part people skip and shouldn't: it says, attempt by attempt, why Playwright couldn't do what you asked.

The mental model: a doctor reads the chart before ordering tests. The error is the chart. Only when it doesn't explain the problem do you reach for the expensive tools: the trace, then running with the Inspector.

This test tries to add the sold-out Vertical Mouse to the cart:

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

test("add the vertical mouse to the cart", 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 page.getByRole("listitem").filter({ hasText: "Vertical Mouse" }).getByRole("button", { name: "Add to cart" }).click({ timeout: 3000 });

  await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
});
npx playwright test
Running 1 test using 1 worker

  ✘  1 [chromium] › tests/sold-out.spec.ts:3:1 › add the vertical mouse to the cart (3.2s)


  1) [chromium] › tests/sold-out.spec.ts:3:1 › add the vertical mouse to the cart ──────────────────

    TimeoutError: locator.click: Timeout 3000ms exceeded.
    Call log:
      - waiting for getByRole('listitem').filter({ hasText: 'Vertical Mouse' }).getByRole('button', { name: 'Add to cart' })
        - locator resolved to <button disabled type="button">Add to cart</button>
      - attempting click action
        2 × waiting for element to be visible, enabled and stable
          - element is not enabled
        - retrying click action
        - waiting 20ms
        2 × waiting for element to be visible, enabled and stable
          - element is not enabled
        - retrying click action
          - waiting 100ms
        3 × waiting for element to be visible, enabled and stable
          - element is not enabled
        - retrying click action
          - waiting 500ms


       7 |   await page.getByRole("button", { name: "Sign in" }).click();
       8 |
    >  9 |   await page.getByRole("listitem").filter({ hasText: "Vertical Mouse" }).getByRole("button", { name: "Add to cart" }).click({ timeout: 3000 });
         |                                                                                                                       ^
      10 |
      11 |   await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
      12 | });
        at <project>/tests/sold-out.spec.ts:9:119

    Error Context: test-results/sold-out-add-the-vertical-mouse-to-the-cart-chromium/error-context.md

  1 failed
    [chromium] › tests/sold-out.spec.ts:3:1 › add the vertical mouse to the cart ───────────────────
What’s happening
  1. What failed: locator.click, with a 3000 ms timeout. It's an action that timed out, not an assertion that saw a wrong value, which already narrows things down: Playwright found something it couldn't act on, or found nothing.
  2. The call log answers which. "waiting for getByRole('listitem')…" then "locator resolved to <button disabled type="button">Add to cart</button>": the element was found. Then the actionability checks (Chapter 5): "attempting click action", "waiting for element to be visible, enabled and stable", "element is not enabled", retrying again and again until the 3 seconds ran out.
  3. So the diagnosis is complete from the text alone: the button exists, is disabled, and Playwright waited for it to become enabled, which never happens because the product is sold out. No trace or debugger needed.
  4. What to do depends on intent. If the test means "a sold-out product can't be added", it should assert that: await expect(button).toBeDisabled(). If it means "a customer can buy the vertical mouse", the test data is wrong (pick a product in stock, or set up stock through the API). Either way, the fix is in the test.
  5. Don't "fix" it with click({ force: true }). Forcing skips the actionability checks, clicks the disabled button, nothing happens, and the next assertion fails with a far more confusing message (Chapter 5).
AdvancedThe error context file

Every failure also writes test-results/<test>/error-context.md. It's written as instructions for an AI assistant (it starts "Explain why, be concise…"; the HTML report's "Copy prompt" button uses it), but it's just as useful to a human because it contains an aria snapshot of the page at the moment of failure (Chapter 10):

show-error-context.mjs
// Prints an error-context.md as the run wrote it, with two changes so it fits this page: its code fences are shown
// as ~~~, and the page snapshot keeps only the Vertical Mouse card (the full one lists the whole page).
import { readFileSync } from "node:fs";
const fence = "\u0060".repeat(3); // three backticks
const text = readFileSync(process.argv[2], "utf8").replaceAll(fence, "~~~");
const [before, rest] = text.split("# Page snapshot");
const [snapshot, after] = rest.split("# Test source");
const lines = snapshot.split("\n");
const start = lines.findIndex((l) => l.includes('"Vertical Mouse"')) - 1;
const indent = lines[start].search(/\S/);
let end = start + 1;
while (end < lines.length && lines[end].search(/\S/) > indent) end++;
console.log(`${before}# Page snapshot (only the Vertical Mouse card)\n\n~~~yaml\n${lines.slice(start, end).join("\n")}\n~~~\n\n# Test source${after}`.trimEnd());
node show-error-context.mjs test-results/sold-out-add-the-vertical-mouse-to-the-cart-chromium/error-context.md
# Instructions

- Following Playwright test failed.
- Explain why, be concise, respect Playwright best practices.
- Provide a snippet of code with the fix, if possible.

# Test info

- Name: sold-out.spec.ts >> add the vertical mouse to the cart
- Location: tests/sold-out.spec.ts:3:1

# Error details

~~~
TimeoutError: locator.click: Timeout 3000ms exceeded.
Call log:
  - waiting for getByRole('listitem').filter({ hasText: 'Vertical Mouse' }).getByRole('button', { name: 'Add to cart' })
    - locator resolved to <button disabled type="button">Add to cart</button>
  - attempting click action
    2 × waiting for element to be visible, enabled and stable
      - element is not enabled
    - retrying click action
    - waiting 20ms
    2 × waiting for element to be visible, enabled and stable
      - element is not enabled
    - retrying click action
      - waiting 100ms
    3 × waiting for element to be visible, enabled and stable
      - element is not enabled
    - retrying click action
      - waiting 500ms

~~~

# Page snapshot (only the Vertical Mouse card)

~~~yaml
      - listitem [ref=f1e36]:
        - heading "Vertical Mouse" [level=2] [ref=f1e37]
        - paragraph [ref=f1e38]: Mice
        - paragraph [ref=f1e39]: $45.00
        - paragraph [ref=f1e40]: Sold out
        - button "Add to cart" [disabled] [ref=f1e41]
~~~

# Test source

~~~ts
  1  | import { test, expect } from "@playwright/test";
  2  | 
  3  | test("add the vertical mouse to the cart", async ({ page }) => {
  4  |   await page.goto("/practice/");
  5  |   await page.getByLabel("Username").fill("ana");
  6  |   await page.getByLabel("Password").fill("playwright");
  7  |   await page.getByRole("button", { name: "Sign in" }).click();
  8  | 
> 9  |   await page.getByRole("listitem").filter({ hasText: "Vertical Mouse" }).getByRole("button", { name: "Add to cart" }).click({ timeout: 3000 });
     |                                                                                                                       ^ TimeoutError: locator.click: Timeout 3000ms exceeded.
  10 | 
  11 |   await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
  12 | });
  13 | 
~~~
What’s happening
  1. Test info and Error details repeat the failure and the call log.
  2. Page snapshot is the page's accessibility tree when the click gave up (the script above kept only the Vertical Mouse card; the real file has the whole page). It reads - paragraph: Sold out and - button "Add to cart" [disabled]: the page telling you why, without opening anything. The [ref=…] ids are there for AI agents, which can use them to point at an element (Chapter 13).
  3. Test source shows the test with the failing line marked. With all three in one file, pasting it into an assistant gives it enough to suggest a fix, and reading it yourself often makes the suggestion unnecessary.
AdvancedInteractive tools: --debug, pause(), UI Mode

The interactive tools: --debug, page.pause(), UI Mode and VS Code

When the error and the trace aren't enough, step through the test live. These tools open windows, so none of them was run for this page; what follows is from the 1.65 docs and CLI help.

ToolCommandWhat it gives you
Playwright Inspectornpx playwright test sold-out.spec.ts:9 --debugheaded browser, stops before each action; step over, resume, live locator editing. --debug is a shortcut for PWDEBUG=1 plus --timeout=0 --max-failures=1 --headed --workers=1
A breakpoint in the testawait page.pause(); then run with --debugstops at that line; "Resume" in the Inspector runs on to the next pause
UI Modenpx playwright test --uiall tests in a sidebar, a timeline with DOM snapshots for every action, watch mode, pick locator
VS Code extensionthe Testing sidebarbreakpoints in your editor, step through, "Pick locator", live locator highlighting
Verbose logsDEBUG=pw:api npx playwright testevery Playwright API call logged to the terminal
Browser launch problemsDEBUG=pw:browser npx playwright testthe browser's own startup output (the CI docs' advice)
An agent attached to a test (1.59+)npx playwright test --debug=clilets a coding agent attach and step through with playwright-cli
TypeScript
test("add the vertical mouse to the cart", async ({ page }) => {
  // … sign in …
  await page.pause(); // stops here when the test runs in debug mode (--debug)
  await page.getByRole("listitem").filter({ hasText: "Vertical Mouse" }).getByRole("button", { name: "Add to cart" }).click();
});

Remove page.pause() before committing; some teams add a lint rule that flags it, much as forbidOnly catches a stray test.only. And --debug sets the test timeout to 0, so a test that "hangs" in the Inspector is waiting for you, not broken.

#Why tests flake

Added

A flaky test passes and fails on the same code. It's worse than a failing test: a failing test is a clear signal, a flaky one teaches the team to ignore red builds, and then the real failure gets ignored too. Almost every flake is the test (or the app) depending on something it doesn't control. The usual suspects:

CauseWhat it looks likeThe real fix
A race with the appasserting a toast after another slow step; reading text before it loadswait for the right condition: a web-first assertion right after the action, or assert something that lasts
Fixed sleepswaitForTimeout(2000) that's enough on your laptop, not on CIdelete it; wait for an event, a response or a state
Shared datatwo tests editing the same account in paralleleach test creates its own data; per-worker accounts; locks (Chapter 12)
Order dependencepasses in the suite, fails alone or shuffledeach test arranges its own state (Chapter 3); --shuffle to find it
Timefails at midnight, on month ends, in another time zonethe clock API and timezoneId (below)
Animations and layout shiftclick lands on the wrong element mid-transitionPlaywright's stability check usually covers it; don't use force: true
The network and the environmentslow or failing third-party calls, an overloaded CI machinemock what you don't own (Chapter 9); fewer workers on small CI machines
Non-deterministic data"the first product" changes when someone adds onelocate by meaning, not position; seed the data

The mental model: a flaky test is a race you haven't seen the start of. There's always a "this happens before that" the test assumes and nobody guarantees. The fix is to find that assumption and replace it with something the test waits for or controls.

The Practice Shop's "Added to your cart" message disappears 3 seconds after it appears. A test that checks it at the wrong moment is a race. To make the race visible every time, this version puts a deliberately slow step between the click and the check:

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

async function signIn(page: 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);
}
const addMouse = (page: Page) =>
  page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
const toast = (page: Page) => page.getByRole("status").filter({ hasText: "Added Wireless Mouse" });

test("❌ racy: checks the message after another slow step", async ({ page }) => {
  await signIn(page);
  await addMouse(page);
  // Any slow step here (a page load, a search, a busy CI machine). This one takes about 3.2 s on purpose.
  await page.getByLabel("Search products").pressSequentially("keyboard", { delay: 400 });
  await expect(toast(page)).toBeVisible();
});

test("✅ checks the message straight after the click that shows it", async ({ page }) => {
  await signIn(page);
  await addMouse(page);
  await expect(toast(page)).toBeVisible();
  await page.getByLabel("Search products").pressSequentially("keyboard", { delay: 400 });
});

test("✅ checks what lasts: the cart count", async ({ page }) => {
  await signIn(page);
  await addMouse(page);
  await page.getByLabel("Search products").pressSequentially("keyboard", { delay: 400 });
  await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
});
npx playwright test
Running 3 tests using 1 worker

  ✘  1 [chromium] › tests/toast.spec.ts:14:1 › ❌ racy: checks the message after another slow step (9.8s)
  ✓  2 [chromium] › tests/toast.spec.ts:22:1 › ✅ checks the message straight after the click that shows it (4.7s)
  ✓  3 [chromium] › tests/toast.spec.ts:29:1 › ✅ checks what lasts: the cart count (4.7s)


  1) [chromium] › tests/toast.spec.ts:14:1 › ❌ racy: checks the message after another slow step ────

    Error: expect(locator).toBeVisible() failed

    Locator: getByRole('status').filter({ hasText: 'Added Wireless Mouse' })
    Expected: visible
    Timeout: 5000ms
    Error: element(s) not found

    Call log:
      - Expect "toBeVisible" getByRole('status').filter({ hasText: 'Added Wireless Mouse' }) with timeout 5000ms
      - waiting for getByRole('status').filter({ hasText: 'Added Wireless Mouse' })


      17 |   // Any slow step here (a page load, a search, a busy CI machine). This one takes about 3.2 s on purpose.
      18 |   await page.getByLabel("Search products").pressSequentially("keyboard", { delay: 400 });
    > 19 |   await expect(toast(page)).toBeVisible();
         |                             ^
      20 | });
      21 |
      22 | test("✅ checks the message straight after the click that shows it", async ({ page }) => {
        at <project>/tests/toast.spec.ts:19:29

    Error Context: test-results/toast-❌-racy-checks-the-message-after-another-slow-step-chromium/error-context.md

  1 failed
    [chromium] › tests/toast.spec.ts:14:1 › ❌ racy: checks the message after another slow step ─────
  2 passed (20.0s)
What’s happening
  1. The racy test clicks Add to cart, which shows the message and starts a 3-second timer to clear it. Then it types "keyboard" one key every 400 ms, about 3.2 seconds. By the time it asserts, the message has already gone.
  2. toBeVisible() retries for its full 5 seconds, but the message never comes back, so it fails with "element(s) not found". Note that the assertion isn't the bug: it waited correctly. The bug is when the test chose to look.
  3. In real life the slow step isn't a deliberate 3.2 seconds. It's a page load that usually takes 2.5 s and on a busy CI machine takes 3.1 s, so the test passes 19 times out of 20. That's what makes it flaky instead of simply failing, and why it's so hard to catch.
  4. The first fix asserts the transient thing straight after the action that causes it, while it's guaranteed to be there; the slow step comes after. The second fix asserts something that lasts: the cart count, which stays "Cart (1)" however slow the machine is. Usually the second is the better test, because the count is the outcome the user cares about (Chapter 3).
  5. The third way, asserting exactly when the message disappears, needs control of time: the clock API at the end of this chapter checks it at 2999 ms and 3000 ms without waiting at all.
AdvancedFinding a flake: --repeat-each

A flake that fails one time in twenty won't show up in one run. --repeat-each=N runs every selected test N times (in parallel, if there are workers to spare); combine it with --grep to hammer one test, and with --workers to add pressure:

npx playwright test --repeat-each=3 --grep straight
Running 3 tests using 3 workers

  ✓  3 [chromium] › tests/toast.spec.ts:22:1 › ✅ checks the message straight after the click that shows it (4.8s)
  ✓  1 [chromium] › tests/toast.spec.ts:22:1 › ✅ checks the message straight after the click that shows it (4.8s)
  ✓  2 [chromium] › tests/toast.spec.ts:22:1 › ✅ checks the message straight after the click that shows it (4.8s)

  3 passed (5.3s)
What’s happening
  1. The fixed test ran three times, each in a fresh context, and passed every time. For a real investigation you'd use 20 to 100 repeats; three keeps this page short.
  2. Repeats are independent tests, so they also run in parallel across workers, which adds the load that often triggers a flake. --workers=1 does the opposite and is the quickest way to check whether tests are interfering with each other.
  3. --shuffle (1.64+) runs files and parallel tests in a random order and prints the seed, so an order-dependent failure can be reproduced with --shuffle=<seed>. Use both regularly in a nightly job, not only when something already looks flaky.

#Retries, flaky reports and quarantine

Added

Retries re-run a failed test, up to N times. When a test fails and then passes on a retry, Playwright doesn't report it as passed: it reports it as flaky. The three outcomes, in the docs' words: passed (passed on the first run), flaky (failed on the first run, passed when retried), failed (failed on the first run and every retry). A retry runs in a fresh worker process with a new browser, so it isn't affected by whatever state the failure left behind.

Retries are a safety net and a detector, not a fix. They stop one bad network moment from failing a whole release, and the flaky count tells you which tests need fixing. The danger is treating "green after retries" as "fine": a suite where 10% of tests are flaky is slow (every flake runs twice) and is hiding real intermittent bugs.

The mental model: a smoke alarm that goes off when you make toast. It's annoying, and the wrong answer is to take the battery out. You either move the toaster (fix the test) or accept the alarm and count how often it fires (track the flakes).

This test simulates a slow environment: on the first attempt the products API takes 6 seconds, longer than the assertion's default 5 seconds; on the retry it's normal (testInfo.retry is 0 on the first attempt, 1 on the first retry):

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

export default defineConfig({
  testDir: "./tests",
  retries: 1,                  // usually: process.env.CI ? 2 : 0
  use: {
    baseURL: "https://rohit-playwright.pages.dev",
    trace: "on-first-retry",
  },
  projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
});
tests/products.spec.ts
import { test, expect } from "@playwright/test";

test("the sign-in page loads", async ({ page }) => {
  await page.goto("/practice/");
  await expect(page.getByRole("heading", { name: "Sign in" })).toBeVisible();
});

test("the shop lists eight products", async ({ page }, testInfo) => {
  if (testInfo.retry === 0) {
    // A slow environment on the first attempt only: the products API takes 6 s.
    await page.route("**/api/products.json", async (route) => {
      await new Promise((r) => setTimeout(r, 6000));
      await route.continue();
    });
  }
  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/products.spec.ts:3:1 › the sign-in page loads (88ms)
  ✘  2 [chromium] › tests/products.spec.ts:8:1 › the shop lists eight products (5.2s)
  ✓  3 [chromium] › tests/products.spec.ts:8:1 › the shop lists eight products (retry #1) (1.5s)


  1) [chromium] › tests/products.spec.ts:8:1 › the shop lists eight products ───────────────────────

    Error: expect(locator).toHaveCount(expected) failed

    Locator:  getByRole('listitem')
    Expected: 8
    Received: 0
    Timeout:  5000ms

    Call log:
      - Expect "toHaveCount" getByRole('listitem') with timeout 5000ms
      - waiting for getByRole('listitem')
        14 × locator resolved to 0 elements
           - unexpected value "0"


      18 |   await page.getByLabel("Password").fill("playwright");
      19 |   await page.getByRole("button", { name: "Sign in" }).click();
    > 20 |   await expect(page.getByRole("listitem")).toHaveCount(8);
         |                                            ^
      21 | });
      22 |
        at <project>/tests/products.spec.ts:20:44

    Error Context: test-results/products-the-shop-lists-eight-products-chromium/error-context.md

  1 flaky
    [chromium] › tests/products.spec.ts:8:1 › the shop lists eight products ────────────────────────
  1 passed (7.5s)
What’s happening
  1. The first test passes normally. The second test's first attempt routes the products API through a 6-second delay, so the shop is still showing "Loading products…" when toHaveCount(8) gives up after its default 5 seconds. The call log shows it: the locator resolved to 0 elements, again and again.
  2. Because retries: 1, Playwright throws that worker away and runs the test again in a fresh one, labelled (retry #1). testInfo.retry is now 1, so there's no delay, and it passes.
  3. The summary says 1 flaky and names the test, then 1 passed. The flaky test isn't counted as passed, and the failure details of the first attempt are printed in full, so a flaky result is never silent.
  4. The exit code is still 0: by default a flaky test doesn't fail the run. Whether it should is a team decision, covered next.
  5. trace: "on-first-retry" recorded a trace of the retry (the attempt that passed). To compare the failing attempt with the passing one, use "retain-on-failure-and-retries" (1.59+) instead.
AdvancedFailing the build on flaky tests: failOnFlakyTests

failOnFlakyTests: true in the config (1.52+), or --fail-on-flaky-tests on the command line, makes a flaky result fail the run. This script runs the suite the way CI does and prints the exit code CI would see, without and then with the flag:

ci-gate.mjs
// Runs the suite like a CI step and prints the exit code: 0 = the job passes, anything else = it fails.
import { spawnSync } from "node:child_process";
const run = spawnSync("npx", ["playwright", "test", "--reporter=dot", ...process.argv.slice(2)], { encoding: "utf8" });
console.log(run.stdout.split("\n").filter((l) => /^[·×±F°T]+$|^\s+\d+ (flaky|passed|failed)/.test(l)).join("\n"));
console.log(`exit code: ${run.status}`);
node ci-gate.mjs
·×±
  1 flaky
  1 passed (7.4s)
exit code: 0
node ci-gate.mjs --fail-on-flaky-tests
·×±
  1 flaky
  1 passed (7.5s)
exit code: 1
What’s happening
  1. The script runs the same suite with the dot reporter and keeps only the progress line and the summary. In the progress line, · is a pass, × a failure that will be retried, and ± a test that turned out flaky (from the reporter docs).
  2. Without the flag: one flaky, one passed, exit code 0. The CI job is green.
  3. With --fail-on-flaky-tests: the identical result, but exit code 1. The CI job is red, and someone has to look at the flake.
  4. Teams use this in two ways: on in the main branch's pipeline from day one (strict: every flake is a bug to fix now), or off, with the flaky count tracked and a budget ("no test may be flaky more than twice a week"). Off with nobody watching is the option that rots.
AdvancedQuarantine: out of the gate, not out of sight

Quarantine: taking a flaky test out of the gate without losing it

When a flaky test can't be fixed today, don't delete it and don't let it keep failing everyone's builds. Quarantine it: keep it running somewhere it can't block a merge, with a ticket and an owner. With Playwright that's a tag plus --grep-invert:

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

async function signIn(page: 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();
}

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

test("sorting by price puts the headphones first", {
  tag: "@quarantine",
  annotation: { type: "issue", description: "SHOP-123: fails about 1 in 30 runs on CI; owner: checkout team" },
}, async ({ page }) => {
  await signIn(page);
  await page.getByLabel("Sort by").selectOption("price-desc");
  await expect(page.getByRole("listitem").first()).toContainText("Noise-Cancelling Headphones");
});

test.fixme("password reset emails a link", async () => {
  // Not built yet. fixme = skipped, and reported as skipped, so it isn't forgotten.
});
npx playwright test --grep-invert @quarantine
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/shop.spec.ts:10:1 › search finds the wireless mouse (1.7s)
  -  2 [chromium] › tests/shop.spec.ts:25:6 › password reset emails a link

  1 skipped
  1 passed (2.0s)
npx playwright test --grep @quarantine
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/shop.spec.ts:16:1 › sorting by price puts the headphones first @quarantine (1.8s)

  1 passed (2.1s)
What’s happening
  1. The quarantined test carries a tag (@quarantine) and an annotation with the ticket and the owner, so the HTML report shows why it's there and who owns it.
  2. The blocking CI job runs --grep-invert @quarantine: the normal test runs, the quarantined one doesn't, and test.fixme shows up as skipped. A merge can't be blocked by a known flake.
  3. A separate, non-blocking job (or a nightly one) runs --grep @quarantine, so the quarantined test keeps running and its flake rate stays visible. When it's fixed and has been stable for a while, remove the tag.
  4. test.fixme is for tests that can't work yet (the feature isn't built, the test is known broken); test.skip with a condition is for tests that don't apply (test.skip(browserName === "webkit", "…")); test.fail() marks a test that's expected to fail because of a known bug, and alerts you when it starts passing.
  5. Quarantine needs rules or it becomes a graveyard: every entry has a ticket, an owner and a date, and the list is reviewed every sprint.
AdvancedRetry strategy and other settings
  • retries in the config, --retries=N on the command line, or per group with test.describe.configure({ retries: 2 }). The generator's default is process.env.CI ? 2 : 0: no retries locally (you want to see flakes), two on CI.
  • retryStrategy (1.62+): "immediate" (the default) retries a failed test as soon as a worker is free, mixed in with the rest of the run; "isolated" runs all retries at the end, one by one in a single worker. Isolated retries are slower but tell you something: a test that fails in the busy parallel run and passes alone is probably sensitive to load or to other tests.
  • In serial mode (test.describe.configure({ mode: "serial" })), a failure skips the rest of the group and the whole group is retried together.
  • testInfo.retry lets a test or fixture behave differently on a retry, for example clearing a server-side cache first (the docs' example). Use it for cleanup, never to make the retry easier to pass.

#Time and the clock API

Added

Anything that depends on time is a trap for tests: a message that disappears after 3 seconds, a session that expires after 30 minutes, a date that's "4 days from today", a countdown, a greeting that changes at noon. Waiting for real time makes tests slow (nobody waits 30 minutes), and comparing with real dates makes them fail on a different day. The clock API (page.clock, or context.clock) replaces the page's notion of time with one the test controls.

There are two levels. setFixedTime(time) only freezes the date: Date.now() and new Date() always return that moment, and timers keep running normally. install({ time }) replaces the timers too (setTimeout, setInterval, requestAnimationFrame, performance, Date and more, per the 1.65 docs), after which you move time yourself: runFor(ms) advances time and fires every timer due on the way, fastForward(ms) jumps ahead and fires due timers once (like opening a laptop lid), pauseAt(time) jumps to a moment and stops, and resume() lets time flow again. setSystemTime changes the date without firing timers (for testing time-zone or clock changes).

The mental model: a film director's clapperboard. The page thinks time passes; actually the test says "action" and "cut", and can jump the scene to next Tuesday without anyone waiting.

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

test.use({ timezoneId: "America/Toronto" });

async function signIn(page: 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("the message disappears exactly 3 seconds after adding", async ({ page }) => {
  await page.clock.install({ time: "2026-11-24T09:55:00-05:00" }); // a little before the moment we care about
  await signIn(page);                                               // time flows normally while the page loads
  await page.clock.pauseAt("2026-11-24T10:00:00-05:00");            // then stop it

  await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
  const message = page.getByRole("status").filter({ hasText: "Added Wireless Mouse" });
  await expect(message).toBeVisible();

  await page.clock.runFor(2999);
  await expect(message).toBeVisible();   // 1 ms before the deadline: still there
  await page.clock.runFor(1);
  await expect(message).toBeHidden();    // at 3000 ms: gone
});

test("standard delivery is estimated 4 days after ordering", async ({ page }) => {
  await page.clock.setFixedTime("2026-12-29T16:30:00-05:00"); // a Tuesday, just before a new year
  await signIn(page);
  await page.getByRole("listitem").filter({ hasText: "USB Microphone" }).getByRole("button", { name: "Add to cart" }).click();
  await page.goto("/practice/checkout");
  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.getByTestId("delivery-estimate")).toHaveText("Estimated delivery: Saturday, January 2");
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/clock.spec.ts:13:1 › the message disappears exactly 3 seconds after adding (1.5s)
  ✓  2 [chromium] › tests/clock.spec.ts:28:1 › standard delivery is estimated 4 days after ordering (2.9s)

  2 passed (4.8s)
What’s happening
  1. The toast test installs the clock at 9:55, before the page loads, as the docs require. Time still flows after install, so sign-in's 500 ms wait and the 700 ms product load happen normally. Then pauseAt(10:00) jumps to 10:00 and stops time: from here on, no timer fires unless the test says so.
  2. The click shows the message and calls setTimeout(…, 3000), which is now the fake setTimeout: it will fire when the fake clock reaches 10:00:03, not after 3 real seconds.
  3. runFor(2999) advances time by 2999 ms, firing anything due on the way (nothing is). The message is still visible. runFor(1) reaches exactly 3000 ms, the timer fires, the shop clears the message, and toBeHidden() passes. The test proved the exact deadline, both sides of it, and waited for none of it in real time.
  4. The delivery test only needs a fixed date, so setFixedTime is enough and timers keep running (the shop's 1.2 s "placing order" wait happens normally). Tuesday 29 December plus 4 days crosses the year: Saturday, January 2. A date edge like a year end, a month end or a daylight-saving change is exactly what you can't wait for in real life and can test any day with the clock.
  5. timezoneId: "America/Toronto" matters in both: at 16:30 in Toronto it's already 21:30 in UTC, so without a fixed time zone the shop could compute a different day on a CI machine in another zone.
AdvancedThe classic trap: pausing time before the page has loaded

Once the clock is paused, the page's own timers stop too: loading spinners, debounces, animations, the shop's "slow on purpose" waits. A test that pauses too early hangs, and the failure doesn't mention the clock at all:

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

test("paused too early: sign-in never finishes", async ({ page }) => {
  await page.clock.install({ time: "2026-11-24T10:00:00-05:00" });
  await page.goto("/practice/");
  await page.clock.pauseAt("2026-11-24T10:01:00-05:00");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();

  await expect(page.getByRole("heading", { name: "Products" })).toBeVisible({ timeout: 3000 });
});

test("paused, then moved on by hand through each delay", async ({ page }) => {
  await page.clock.install({ time: "2026-11-24T10:00:00-05:00" });
  await page.goto("/practice/");
  await page.clock.pauseAt("2026-11-24T10:01:00-05:00");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page.getByRole("button", { name: "Signing in…" })).toBeDisabled();

  await page.clock.runFor(500);   // the shop's sign-in delay
  await expect(page.getByText("Loading products…")).toBeVisible();
  await page.clock.runFor(700);   // the shop's product-loading delay
  await expect(page.getByRole("listitem")).toHaveCount(8);
});
npx playwright test
Running 2 tests using 1 worker

  ✘  1 [chromium] › tests/clock-trap.spec.ts:3:1 › paused too early: sign-in never finishes (3.1s)
  ✓  2 [chromium] › tests/clock-trap.spec.ts:14:1 › paused, then moved on by hand through each delay (217ms)


  1) [chromium] › tests/clock-trap.spec.ts:3:1 › paused too early: sign-in never finishes ──────────

    Error: expect(locator).toBeVisible() failed

    Locator: getByRole('heading', { name: 'Products' })
    Expected: visible
    Timeout: 3000ms
    Error: element(s) not found

    Call log:
      - Expect "toBeVisible" getByRole('heading', { name: 'Products' }) with timeout 3000ms
      - waiting for getByRole('heading', { name: 'Products' })


       9 |   await page.getByRole("button", { name: "Sign in" }).click();
      10 |
    > 11 |   await expect(page.getByRole("heading", { name: "Products" })).toBeVisible({ timeout: 3000 });
         |                                                                 ^
      12 | });
      13 |
      14 | test("paused, then moved on by hand through each delay", async ({ page }) => {
        at <project>/tests/clock-trap.spec.ts:11:65

    Error Context: test-results/clock-trap-paused-too-early-sign-in-never-finishes-chromium/error-context.md

  1 failed
    [chromium] › tests/clock-trap.spec.ts:3:1 › paused too early: sign-in never finishes ───────────
  1 passed (4.1s)
What’s happening
  1. The first test pauses the clock at 10:01 and then signs in. The shop's sign-in handler calls await wait(500), a setTimeout, which is now frozen. The button says "Signing in…" forever and the products heading never appears; the test fails after 3 seconds with an ordinary "element(s) not found". Nothing in the error says "clock". If you see a page stuck mid-loading in a test that uses the clock, this is the first thing to check.
  2. The second test pauses at the same moment but drives time through each delay: runFor(500) fires the sign-in timer, the browser navigates to the shop, and the shop shows "Loading products…"; runFor(700) fires the loading timer and the 8 products appear. The paused clock carried over to the new page, because it belongs to the browser context, not to one page.
  3. This is powerful (every delay is under the test's control and nothing waits in real time) but brittle: the test now knows the app's internal timings. The docs' advice is the safer default: install a little before the moment you care about, let the page load with time flowing, then pauseAt, as the main example did.
AdvancedWhich clock method to use
You want to testUse
a date shown on the page ("delivered by…", "member since…")setFixedTime
a timeout or countdown fires at the right momentinstall, pauseAt, runFor
"after 30 minutes idle you're logged out"install, then fastForward("30:00")
what happens when the system clock jumps (DST, time zone travel)install, then setSystemTime
the same date in every time zonesetFixedTime plus timezoneId in test.use or the config

Two rules from the docs: if you install, do it before any other clock call, and set the clock up before the page loads so the app never sees real time. And the clock only fakes the browser's time; your backend still uses the real clock, so a token signed by the server can still expire for real.

#Your turn: debug and steady two tests

Added
Your turn: read the error, fix the test

This test fails. Without running anything else, use the error to say why, then fix it so it tests what its title says.

TypeScript
test("ana can add the compact keyboard", 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 page.getByRole("button", { name: "Add to cart" }).click();
  await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
});
Show answer

Here's the run of that test, then the fixed test:

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

test("as written: ana can add the compact keyboard", 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 page.getByRole("button", { name: "Add to cart" }).click({ timeout: 3000 });
  await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
});

test("fixed: ana can add the compact keyboard", 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 page.getByRole("listitem").filter({ hasText: "Compact Keyboard" }).getByRole("button", { name: "Add to cart" }).click();
  await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
  await expect(page.getByRole("status").filter({ hasText: "Added" })).toHaveText("Added Compact Keyboard to your cart");
});
npx playwright test
Running 2 tests using 1 worker

  ✘  1 [chromium] › tests/keyboard.spec.ts:3:1 › as written: ana can add the compact keyboard (1.5s)
  ✓  2 [chromium] › tests/keyboard.spec.ts:12:1 › fixed: ana can add the compact keyboard (1.5s)


  1) [chromium] › tests/keyboard.spec.ts:3:1 › as written: ana can add the compact keyboard ────────

    Error: locator.click: Error: strict mode violation: getByRole('button', { name: 'Add to cart' }) resolved to 8 elements:
        1) <button type="button" data-add="kb-01">Add to cart</button> aka getByTestId('product-kb-01').getByRole('button', { name: 'Add to cart' })
        2) <button type="button" data-add="kb-02">Add to cart</button> aka getByTestId('product-kb-02').getByRole('button', { name: 'Add to cart' })
        3) <button type="button" data-add="ms-01">Add to cart</button> aka getByTestId('product-ms-01').getByRole('button', { name: 'Add to cart' })
        4) <button disabled type="button">Add to cart</button> aka getByTestId('product-ms-02').getByRole('button', { name: 'Add to cart' })
        5) <button type="button" data-add="au-01">Add to cart</button> aka getByTestId('product-au-01').getByRole('button', { name: 'Add to cart' })
        6) <button type="button" data-add="au-02">Add to cart</button> aka getByTestId('product-au-02').getByRole('button', { name: 'Add to cart' })
        7) <button type="button" data-add="dk-01">Add to cart</button> aka locator('li:nth-child(7) > button')
        8) <button type="button" data-add="dk-02">Add to cart</button> aka locator('li:nth-child(8) > button')

    Call log:
      - waiting for getByRole('button', { name: 'Add to cart' })


       6 |   await page.getByLabel("Password").fill("playwright");
       7 |   await page.getByRole("button", { name: "Sign in" }).click();
    >  8 |   await page.getByRole("button", { name: "Add to cart" }).click({ timeout: 3000 });
         |                                                           ^
       9 |   await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
      10 | });
      11 |
        at <project>/tests/keyboard.spec.ts:8:59

    Error Context: test-results/keyboard-as-written-ana-can-add-the-compact-keyboard-chromium/error-context.md

  1 failed
    [chromium] › tests/keyboard.spec.ts:3:1 › as written: ana can add the compact keyboard ─────────
  1 passed (3.8s)
What’s happening
  1. The error is a strict mode violation: getByRole('button', { name: 'Add to cart' }) resolved to 8 elements, one per product, and the call log lists them. Playwright refuses to guess which one you meant (Chapter 4).
  2. The title says "compact keyboard", but the locator never mentions it: the test was written as if there were one product. The fix scopes the locator to the card that contains "Compact Keyboard", then finds its button.
  3. The fixed test also checks the message names the right product. "Cart (1)" alone would pass if any product were added, which is exactly how the .first() bug in the Trace Viewer example slipped through.
  4. Don't fix a strict mode violation with .first() or .nth(1). It makes the error go away by picking an element by position, which breaks as soon as the order changes.
Your turn: test the 3-second message without waiting 3 seconds

Write a test that adds a product and checks the "Added" message is gone after 3 seconds, using the clock so the test doesn't wait in real time. Use fastForward this time.

Show answer
tests/toast-clock.spec.ts
import { test, expect } from "@playwright/test";

test("the added message is cleared after 3 seconds", async ({ page }) => {
  await page.clock.install();
  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.getByRole("listitem")).toHaveCount(8);

  await page.getByRole("listitem").filter({ hasText: "Standing Desk Mat" }).getByRole("button", { name: "Add to cart" }).click();
  const message = page.getByRole("status").filter({ hasText: "Added Standing Desk Mat" });
  await expect(message).toBeVisible();

  await page.clock.fastForward("03"); // "03" = 3 seconds
  await expect(message).toBeHidden({ timeout: 500 });
  await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
});
npx playwright test
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/toast-clock.spec.ts:3:1 › the added message is cleared after 3 seconds (1.5s)

  1 passed (2.0s)
What’s happening
  1. page.clock.install() with no time starts the fake clock at the current time, before the page loads. Time still flows, so sign-in and the product load work normally.
  2. After the click, the message is visible and its 3-second timer is waiting on the fake clock.
  3. fastForward("03") jumps the clock 3 seconds ahead and fires the due timer once (the string format is seconds, "01:00" would be a minute). The message is cleared immediately.
  4. toBeHidden({ timeout: 500 }) proves it disappeared because of the jump, not because 3 real seconds passed: half a second wouldn't be enough for the real timer. The cart count shows the product is still in the cart; only the message went.
  5. The difference from runFor: fastForward skips straight to the end and fires due timers once, like waking a sleeping laptop; runFor plays every timer on the way. For "is it gone after N seconds" either works; for an interval that should tick several times, use runFor.

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.