Playwright NotesRohit’s interview study guide
Chapter 06

Assertions

How Playwright decides a test passed: web-first assertions that retry until the page is right, the assertions you'll use every day, negation, soft assertions and custom messages, expect.poll and toPass for things that aren't on the page, and the one-line mistake behind most flaky tests. 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.

#Web-first assertions retry

Added

An assertion is where a test says what must be true. In most test frameworks, expect(x).toBe(y) checks once: x is whatever it was at that instant. A web page doesn't work like that. After a click, the cart count, the toast and the URL all change a moment later, after a request, a timer or a re-render. Checking once means checking too early.

So Playwright's assertions on locators and pages are web-first: await expect(locator).toHaveText("…") looks at the page, and if it isn't right yet, looks again, and again, until it matches or the timeout runs out. The default is 5 seconds, set with expect: { timeout } in the config or { timeout } on one assertion. When it fails, the error shows what it saw on its last look and a call log of how many times it looked.

There are two kinds of expect, and telling them apart is the most important skill in this chapter:

  • await expect(locator or page).toSomething(): retries. It's async, so it must be awaited. Use it for anything on the page.
  • expect(value).toSomething(): checks once, like Jest. Use it for values you already have and that won't change: a number you computed, a response's status, a downloaded file's contents.

The mental model: a web-first assertion is someone watching the page for you, ready to say "yes, there it is" the moment it appears, and giving up only after 5 seconds of nothing. expect(value) is a photo: whatever it shows is fixed, even if the page changes a millisecond later.

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

async function signIn(page: Page, path = "/practice/shop") {
  await page.goto(path);
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page).toHaveURL(path);
}
const addButton = (page: Page, product: string) =>
  page.getByRole("listitem").filter({ hasText: product }).getByRole("button", { name: "Add to cart" });

test("the toast: wait for it to appear, then wait for it to go", async ({ page }) => {
  await signIn(page);
  await addButton(page, "Wireless Mouse").click();
  const toast = page.getByRole("status").filter({ hasText: "Added" });

  await expect(toast).toHaveText("Added Wireless Mouse to your cart");
  await expect(toast).toBeHidden(); // the shop clears it after 3 s: inside the 5 s default
});

test("expect(value) is for values you already have", async ({ page }) => {
  await signIn(page);
  const products = page.getByRole("list", { name: "Products" }).getByRole("listitem");
  await expect(products).toHaveCount(8); // web-first: wait for the page

  const prices = (await products.getByText("$").allTextContents()).map((p) => Number(p.slice(1)));
  expect(Math.min(...prices)).toBe(29.5); // a plain value: checking once is right
  expect(prices).toHaveLength(8);
});

test("a web-first assertion that never comes true", async ({ page }) => {
  await signIn(page);
  await addButton(page, "Wireless Mouse").click();
  await expect(page.getByRole("link", { name: /Cart/ })).toHaveText("Cart (2)", { timeout: 2000 });
});
npx playwright test
Running 3 tests using 1 worker

  ✓  1 [chromium] › tests/retry.spec.ts:13:1 › the toast: wait for it to appear, then wait for it to go (5.1s)
  ✓  2 [chromium] › tests/retry.spec.ts:22:1 › expect(value) is for values you already have (1.7s)
  ✘  3 [chromium] › tests/retry.spec.ts:32:1 › a web-first assertion that never comes true (3.7s)


  1) [chromium] › tests/retry.spec.ts:32:1 › a web-first assertion that never comes true ───────────

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

    Locator:  getByRole('link', { name: /Cart/ })
    Expected: "Cart (2)"
    Received: "Cart (1)"
    Timeout:  2000ms

    Call log:
      - Expect "toHaveText" getByRole('link', { name: /Cart/ }) with timeout 2000ms
      - waiting for getByRole('link', { name: /Cart/ })
        21 × locator resolved to <a class="button" data-cart-link="" href="/practice/cart">Cart (1)</a>
           - unexpected value "Cart (1)"


      33 |   await signIn(page);
      34 |   await addButton(page, "Wireless Mouse").click();
    > 35 |   await expect(page.getByRole("link", { name: /Cart/ })).toHaveText("Cart (2)", { timeout: 2000 });
         |                                                          ^
      36 | });
      37 |
        at <project>/tests/retry.spec.ts:35:58

    Error Context: test-results/retry-a-web-first-assertion-that-never-comes-true-chromium/error-context.md

  1 failed
    [chromium] › tests/retry.spec.ts:32:1 › a web-first assertion that never comes true ────────────
  2 passed (11.0s)
What’s happening
  1. The toast. After the click, toHaveText keeps reading the status region until it says "Added Wireless Mouse to your cart". Then toBeHidden keeps looking until the toast is gone: the shop clears it after 3 seconds, so this assertion waits about 3 seconds and passes, because 3 is less than the 5-second default. If the toast stayed for 6 seconds, it would fail.
  2. Values you already have. toHaveCount(8) waits for the products. Only then does the test read every price once with allTextContents() and turn them into numbers. From here on they're plain values, nothing is going to change them, so expect(…).toBe(29.5) checking once is exactly right.
  3. Never true (fails on purpose). One click makes the cart link "Cart (1)", and the test expects "Cart (2)". The assertion looks again and again for 2 seconds (the timeout passed to it) and then fails.
  4. The error is the useful part: "Expected", "Received" (what it saw on its last look), and a call log line "N × locator resolved to <a class="button" data-cart-link="" href="/practice/cart">Cart (1)</a>" with unexpected value "Cart (1)". The count is how many times it looked; it changes from run to run. You can read the whole story: the right element, the wrong text, the whole time.
AdvancedChanging the timeout, and when not to
  • For the whole project: expect: { timeout: 10_000 } in playwright.config.ts. Do this when your app is consistently slower (a heavy staging environment), not to paper over one slow screen.
  • For one assertion: await expect(locator).toBeVisible({ timeout: 15_000 }), with a comment saying what's slow ("the report takes up to 12 s to generate").
  • For a group of assertions: const slowExpect = expect.configure({ timeout: 15_000 }) (1.34+) gives you an expect with its own defaults.
  • Don't raise the timeout to fix flakiness. If an assertion sometimes needs 6 seconds and sometimes 4, ask why it varies: a slow query, a race, a missing wait for the right thing. A bigger timeout makes failures slower and rarer, not gone.
  • The test timeout (30 s by default) still applies: an assertion with a 60-second timeout inside a 30-second test fails at 30.

#The assertions you use every day

Added

Playwright has about thirty web-first matchers. A dozen cover nearly every test:

AssertionPasses whenWatch out for
toBeVisible() / toBeHidden()the element is (not) visible; hidden also passes if it doesn't existtoBeHidden on a typo'd locator passes too
toHaveText(text)the whole text matches (string: whitespace normalised; regex: as is)a string means the full text, not a part
toContainText(text)the text contains itweaker; fine for long paragraphs
toHaveText([…])a list has exactly these texts, in orderalso checks the count
toHaveValue(value)an input's current valuenot toHaveText, which reads text content
toHaveCount(n)the locator matches exactly n elementstoHaveCount(0) is "none exist"
toHaveAttribute(name, value)the attribute has that valuetest the user-facing state where you can
toHaveClass(…) / toContainClass(…) (1.52+)the full class list / these classes among othersclasses are implementation details
toBeChecked(), toBeEnabled(), toBeDisabled(), toBeEditable(), toBeFocused(), toBeEmpty()the element's statetoBeEmpty means no text or empty value
toHaveAccessibleName(…), toHaveRole(…) (1.44+)what assistive tech seesgreat for icon buttons
expect(page).toHaveURL(…), toHaveTitle(…)the page's URL / <title>relative URLs use baseURL
expect(response).toBeOK()an API response's status is 200–299for request and waitForResponse results

The mental model: assert the user's view in the user's words. Text a user reads, a value in a field they typed into, a count of rows they see, a disabled button they can't press. Reach for attributes and classes only when they are what the user experiences (like aria-invalid on a field marked as wrong).

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

async function signIn(page: Page, path = "/practice/shop") {
  await page.goto(path);
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page).toHaveURL(path);
}

test("the shop and the cart", async ({ page }) => {
  await signIn(page);
  await expect(page).toHaveTitle("Products · Practice Shop");
  await expect(page.getByLabel("Search products")).toBeEmpty();
  const products = page.getByRole("list", { name: "Products" }).getByRole("listitem");
  await expect(products).toHaveCount(8);
  await expect(products.first()).toHaveClass("product");
  await expect(products.filter({ hasText: "Vertical Mouse" }).getByRole("button")).toBeDisabled();

  await page.getByLabel("Category").selectOption("Keyboards");
  await expect(products.getByRole("heading")).toHaveText(["Mechanical Keyboard", "Compact Keyboard"]);
  await products.filter({ hasText: "Compact Keyboard" }).getByRole("button", { name: "Add to cart" }).click();

  await page.getByRole("link", { name: "Cart (1)" }).click();
  await expect(page).toHaveURL("/practice/cart");
  await expect(page.getByRole("row", { name: /Compact Keyboard/ })).toContainText("$59.00");
  await expect(page.getByRole("button", { name: /^Decrease/ })).toHaveAccessibleName("Decrease quantity of Compact Keyboard");
});

test("checkout validation", async ({ page }) => {
  await signIn(page);
  await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
  await page.getByRole("link", { name: "Cart (1)" }).click();
  await page.getByRole("link", { name: "Checkout" }).click();
  await expect(page.getByLabel("Full name")).toHaveValue("Rohit");
  await expect(page.getByLabel("Standard")).toBeChecked();

  await page.getByLabel("Email").fill("rohit@");
  await page.getByRole("button", { name: "Place order" }).click();

  await expect(page.getByRole("alert")).toHaveText("Please fix 3 problems before placing your order.");
  await expect(page.getByLabel("Email")).toHaveAttribute("aria-invalid", "true");
  await expect(page.getByLabel("Email")).toBeFocused();
  await expect(page.getByText("Enter a valid email, like name@example.com.")).toBeVisible();
  await expect(page.getByLabel("Full name")).not.toHaveAttribute("aria-invalid");
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/everyday.spec.ts:11:1 › the shop and the cart (1.9s)
  ✓  2 [chromium] › tests/everyday.spec.ts:30:1 › checkout validation (1.9s)

  2 passed (4.2s)
What’s happening
  1. toHaveTitle checks the <title>, and toBeEmpty the search box (an input is empty when its value is ""). toHaveCount(8) waits for the products.
  2. toHaveClass("product") passes because the card's whole class attribute is exactly product; with a string, toHaveClass compares the full list, so toContainClass (1.52+) is the one to use when an element has several classes and you care about one. toBeDisabled checks the sold-out button can't be pressed: a user-facing rule.
  3. After choosing "Keyboards", toHaveText([...]) on the headings checks there are exactly two products and both names, in order. It's one assertion that retries as a whole.
  4. On the cart, toHaveURL("/practice/cart") is resolved against baseURL. toContainText("$59.00") checks the row includes the price without spelling out the whole row. toHaveAccessibleName checks the − button's name: its visible text is just "−", so this is the only way to know a screen reader says something useful.
  5. On checkout, toHaveValue("Rohit") reads the prefilled field's value (not its text), and toBeChecked the default delivery option.
  6. Submitting with only a bad email gives 3 problems (email, address, terms; the name was prefilled). The test checks the summary alert, that the email field is marked aria-invalid="true" (that's what makes a screen reader say "invalid"), that the shop moved focus to it, and the field's message. The last line uses not with no value: the name field must not have aria-invalid at all.
AdvancedtoHaveText, exactly
  • A string must match the element's whole text, after collapsing whitespace and line breaks: toHaveText("Cart") fails on "Cart (1)". Use toContainText("Cart") or a regex /Cart/ for part of it.
  • A regex is matched against the raw text, so /^Cart \(\d+\)$/ is precise.
  • ignoreCase: true is available on both. useInnerText: true reads innerText (what's rendered) instead of textContent (which includes hidden text, like the cart's visually hidden "Remove" header).
  • An array checks a list: toHaveText([...]) needs exactly that many elements with those texts in order; toContainText([...]) needs a subset, in order, each containing its text.
  • For inputs use toHaveValue: the text content of an <input> is always empty.

#Negation, soft assertions and custom messages

Added

Three tools that change how an assertion behaves, rather than what it checks:

  • .not flips any matcher: await expect(locator).not.toBeVisible(). Web-first negations retry too: they wait until the condition is false. So not.toHaveText("1") after a click waits for the text to change, which is often exactly what you want.
  • expect.soft(…) records a failure and lets the test carry on, then marks it failed at the end with every soft failure listed. Use it when one run should report several independent facts (the five lines of an order summary), so you see all the broken ones at once instead of fixing them one run at a time.
  • A custom message, expect(locator, "the cart badge counts the mouse").toHaveText(…), puts your words at the top of the error and in its call log, above the usual details. It's worth it when the locator alone wouldn't tell a reader why the value matters.

The mental model: a normal assertion is a gate, a soft assertion is a checklist. A gate stops you at the first failure; a checklist lets you walk through every item and hands you the list of what was wrong.

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

export default defineConfig({
  testDir: "./tests",
  expect: { timeout: 2000 }, // shorter than the 5 s default, so the failures below come quickly
  use: { baseURL: "https://rohit-playwright.pages.dev" },
  projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
});
tests/soft.spec.ts
import { test, expect, type Page } from "@playwright/test";

async function signInWithCart(page: Page, ...products: string[]) {
  await page.goto("/practice/shop");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  for (const name of products) {
    await page.getByRole("listitem").filter({ hasText: name }).getByRole("button", { name: "Add to cart" }).click();
  }
  await page.getByRole("link", { name: `Cart (${products.length})` }).click();
}

test("not waits for something to stop being true", async ({ page }) => {
  await signInWithCart(page, "USB Microphone");
  const quantity = page.getByRole("status", { name: "Quantity of USB Microphone" });
  await page.getByRole("button", { name: "Increase quantity of USB Microphone" }).click();
  await expect(quantity).not.toHaveText("1");
  await page.getByRole("button", { name: "Remove USB Microphone" }).click();
  await expect(page.getByRole("table")).not.toBeVisible();
});

test("soft assertions report every wrong line of the summary", async ({ page }) => {
  await signInWithCart(page, "Wireless Mouse", "Monitor Light Bar");
  await page.getByRole("link", { name: "Checkout" }).click();
  const summary = page.getByRole("complementary", { name: "Order summary" });

  // Two expectations below are wrong on purpose, to show what a soft failure report looks like.
  await expect.soft(summary.getByText("Wireless Mouse × 1")).toBeVisible();
  await expect.soft(summary.getByText("Monitor Light Bar × 2"), "the light bar line shows the quantity in the cart").toBeVisible();
  await expect.soft(page.getByTestId("order-total"), "the total is the two prices with free delivery").toHaveText("$78.00");
  await expect.soft(summary).toContainText("Free");

  await page.getByLabel("Express").check(); // the test carried on after the soft failures
  await expect(page.getByTestId("order-total")).toHaveText("$88.49");
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/soft.spec.ts:14:1 › not waits for something to stop being true (1.6s)
  ✘  2 [chromium] › tests/soft.spec.ts:23:1 › soft assertions report every wrong line of the summary (5.6s)


  1) [chromium] › tests/soft.spec.ts:23:1 › soft assertions report every wrong line of the summary ─

    Error: the light bar line shows the quantity in the cart

    expect(locator).toBeVisible() failed

    Locator: getByRole('complementary', { name: 'Order summary' }).getByText('Monitor Light Bar × 2')
    Expected: visible
    Timeout: 2000ms
    Error: element(s) not found

    Call log:
      - the light bar line shows the quantity in the cart getByRole('complementary', { name: 'Order summary' }).getByText('Monitor Light Bar × 2') with timeout 2000ms
      - waiting for getByRole('complementary', { name: 'Order summary' }).getByText('Monitor Light Bar × 2')


      28 |   // Two expectations below are wrong on purpose, to show what a soft failure report looks like.
      29 |   await expect.soft(summary.getByText("Wireless Mouse × 1")).toBeVisible();
    > 30 |   await expect.soft(summary.getByText("Monitor Light Bar × 2"), "the light bar line shows the quantity in the cart").toBeVisible();
         |                                                                                                                      ^
      31 |   await expect.soft(page.getByTestId("order-total"), "the total is the two prices with free delivery").toHaveText("$78.00");
      32 |   await expect.soft(summary).toContainText("Free");
      33 |
        at <project>/tests/soft.spec.ts:30:118

    Error: the total is the two prices with free delivery

    expect(locator).toHaveText(expected) failed

    Locator:  getByTestId('order-total')
    Expected: "$78.00"
    Received: "$78.50"
    Timeout:  2000ms

    Call log:
      - the total is the two prices with free delivery getByTestId('order-total') with timeout 2000ms
      - waiting for getByTestId('order-total')
        21 × locator resolved to <span data-testid="order-total">$78.50</span>
           - unexpected value "$78.50"


      29 |   await expect.soft(summary.getByText("Wireless Mouse × 1")).toBeVisible();
      30 |   await expect.soft(summary.getByText("Monitor Light Bar × 2"), "the light bar line shows the quantity in the cart").toBeVisible();
    > 31 |   await expect.soft(page.getByTestId("order-total"), "the total is the two prices with free delivery").toHaveText("$78.00");
         |                                                                                                        ^
      32 |   await expect.soft(summary).toContainText("Free");
      33 |
      34 |   await page.getByLabel("Express").check(); // the test carried on after the soft failures
        at <project>/tests/soft.spec.ts:31:104

    Error Context: test-results/soft-soft-assertions-report-every-wrong-line-of-the-summary-chromium/error-context.md

  1 failed
    [chromium] › tests/soft.spec.ts:23:1 › soft assertions report every wrong line of the summary ──
  1 passed (7.7s)
What’s happening
  1. The config sets the assertion timeout to 2 seconds for the whole suite, to keep the deliberate failures short. It's the same setting you'd raise for a slow app.
  2. Negation. After +, not.toHaveText("1") waits until the quantity is anything but 1 (it's 2). After Remove, the cart shows "Your cart is empty." and not.toBeVisible() waits for the table to disappear. Both retry, like every web-first assertion.
  3. Soft assertions. The order summary is an <aside aria-label="Order summary">, which has the role complementary. Four soft assertions check its lines. Two of them are wrong on purpose: there's one light bar, not two, and the total is $78.50, not $78.00.
  4. Each wrong soft assertion waits its 2 seconds, records a failure, and the test keeps going: it chooses Express and checks the new total ($88.49), which passes. At the end, the test is marked failed and the report lists both soft failures, in order, each with its own code frame.
  5. Custom messages. The two failures carry the messages passed as expect's second argument ("the light bar line shows the quantity in the cart", "the total is the two prices with free delivery") at the top of their errors, followed by the usual locator, expected and received values. Without them you'd see only the locator and the expected value, and have to work out the intent.
AdvancedSoft assertions: when, and when not
  • Good for: several independent facts about one screen (a summary, a profile page, the columns of a row), where knowing all the failures at once saves reruns.
  • Bad for: steps that depend on each other. If "the order was placed" fails softly, everything after it fails for the same reason and buries the real error. Keep the flow with normal assertions and use soft ones for the details.
  • Stop early if they failed: expect(test.info().errors).toHaveLength(0) after a group of soft assertions turns them back into a gate before an expensive next step.
  • expect.configure({ soft: true }) (1.34+) makes an expect whose assertions are all soft, if a whole block is a checklist.
  • Soft assertions only work in the Playwright test runner.
Advancednot.toBeVisible and toBeHidden pass for missing elements

#expect.poll and toPass

Added

Web-first assertions work on locators and pages. Sometimes the thing you need to wait for isn't on the page: a value in localStorage, a counter in a database, an API's response, a file being written. Or it's a sequence of steps that has to be retried together. For those, Playwright has two helpers:

  • expect.poll(fn).matcher(…) calls fn repeatedly until its result passes the matcher. fn can be anything async: page.evaluate, an API call with request, a database query. Defaults from the docs: timeout 5 seconds, and it polls at intervals of 100, 250, 500, then every 1000 ms.
  • expect(async () => { … }).toPass() runs a whole block again and again until it doesn't throw. Inside, you use ordinary actions and assertions. Same intervals by default, but the default timeout is 0, meaning it can retry until the test times out, so always pass { timeout }.

The mental model: expect.poll asks a question over and over; toPass does a chore over and over. "What's in storage now?" is a question. "Reload the page and look for the order" is a chore.

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

async function signIn(page: Page, path = "/practice/shop") {
  await page.goto(path);
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page).toHaveURL(path);
}
const savedCart = (page: Page) =>
  page.evaluate(() => (JSON.parse(localStorage.getItem("shop-cart") ?? "[]") as { name: string; qty: number }[]).map((l) => `${l.name} × ${l.qty}`));

test("expect.poll: what the shop saved in localStorage", async ({ page }) => {
  await signIn(page);
  const add = page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" });
  await add.click();
  await add.click();

  await expect.poll(() => savedCart(page)).toEqual(["Wireless Mouse × 2"]);
});

test("expect.poll: the order counter, while the order is still being placed", async ({ page }) => {
  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.poll(() => page.evaluate(() => localStorage.getItem("shop-orders")), { message: "one order was counted" }).toBe("1001");
});

test("toPass: reload the other tab until the order shows up", async ({ page, context }) => {
  await signIn(page);
  const account = await context.newPage(); // same context, so already signed in
  await account.goto("/practice/account");
  await expect(account.getByText("No orders yet.")).toBeVisible();

  await page.getByRole("listitem").filter({ hasText: "Standing Desk Mat" }).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(async () => {
    await account.reload();
    await expect(account.getByRole("rowheader", { name: "ORD-1001" })).toBeVisible({ timeout: 500 });
  }).toPass({ timeout: 10_000 });
  await expect(account.getByRole("row", { name: /ORD-1001/ })).toContainText("$39.00");
});
npx playwright test
Running 3 tests using 1 worker

  ✓  1 [chromium] › tests/poll.spec.ts:13:1 › expect.poll: what the shop saved in localStorage (1.8s)
  ✓  2 [chromium] › tests/poll.spec.ts:22:1 › expect.poll: the order counter, while the order is still being placed (3.7s)
  ✓  3 [chromium] › tests/poll.spec.ts:34:1 › toPass: reload the other tab until the order shows up (3.3s)

  3 passed (9.1s)
What’s happening
  1. The cart in storage. savedCart reads the shop's shop-cart key and turns each line into "name × qty". expect.poll calls it until it equals ["Wireless Mouse × 2"]. The shop saves synchronously on click, so it passes on the first try here; on an app that saves after a debounce or a request, the same line would quietly wait.
  2. The order counter. "Place order" starts a 1.2-second "server call" before the shop writes shop-orders. The poll starts immediately after the click and keeps asking until the value is "1001". The message option labels the assertion in the report if it fails. Chapter 3 read this counter once, after waiting for the confirmation page; expect.poll doesn't need the page to say anything.
  3. Another tab. context.newPage() opens a second tab in the same context (same localStorage, so it's signed in). Its account page says "No orders yet." Pages don't update each other: the account tab only learns about the order when it reloads.
  4. The first tab places an order. toPass then runs its block (reload, look for ORD-1001 for half a second) until it passes. The first attempts fail because the order is still being placed; once the shop has saved it, a reload shows the row and the block passes. The inner assertion has a short timeout so each attempt is quick; the outer timeout of 10 seconds limits the whole thing.
  5. After toPass, an ordinary assertion checks the row's total, $39.00. This "reload until the backend has it" pattern is common with real backends: search indexes, queues and caches that catch up a few seconds later.
AdvancedPolling an API, and toPass safety

expect.poll works with the request fixture (Chapter 9) for things only an API can tell you:

await expect.poll(async () => (await request.get("/api/orders/1001")).status(), { timeout: 15_000 }).toBe(200);

Two rules for toPass:

  • The block must be safe to repeat. Reloading and reading are fine. Clicking "Add to cart" inside toPass could add the product five times before the assertion passes. If a step changes data, it belongs before the block, not in it.
  • Keep inner timeouts short (a second or less), or a single attempt eats the whole budget and the retry never happens.

#The classic flaky assertion

Added

Here it is, the line behind more flaky Playwright tests than any other:

expect(await locator.textContent()).toBe("…")

It looks like a web-first assertion, but the await is in the wrong place. await locator.textContent() reads the text once, right now, and hands a plain string to a plain expect, which has nothing to retry. The same goes for count(), isVisible(), inputValue() and getAttribute() wrapped in expect(await …). The docs' best-practices page gives this exact example, expect(await page.getByText('welcome').isVisible()).toBe(true), and says such a test "won't wait a single second".

Why "flaky" and not just "broken"? Because whether it passes depends on how fast the page is compared to the test. If the update usually lands before the read, the test passes on your laptop. On a busy CI machine, the read sometimes wins the race, and the test fails for no visible reason.

The mental model: move the await outside the expect, and give expect the locator, not the value. await expect(locator).toHaveText("…") hands Playwright the recipe, so it can look as many times as it needs.

The shop's search applies 0.3 seconds after the last keystroke, which is long enough that the bad versions fail every time here, instead of only sometimes:

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

async function signIn(page: Page, path = "/practice/shop") {
  await page.goto(path);
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page).toHaveURL(path);
}

test.beforeEach(async ({ page }) => {
  await signIn(page);
  await expect(page.getByRole("listitem")).toHaveCount(8);
});

test("❌ count() read once", async ({ page }) => {
  await page.getByLabel("Search products").fill("mouse");
  expect(await page.getByRole("listitem").count()).toBe(2);
});

test("❌ isVisible() read once", async ({ page }) => {
  await page.getByLabel("Search products").fill("lamp");
  expect(await page.getByText("No products match “lamp”.").isVisible()).toBe(true);
});

test("✅ toHaveCount retries", async ({ page }) => {
  await page.getByLabel("Search products").fill("mouse");
  await expect(page.getByRole("listitem")).toHaveCount(2);
});

test("✅ toBeVisible retries", async ({ page }) => {
  await page.getByLabel("Search products").fill("lamp");
  await expect(page.getByText("No products match “lamp”.")).toBeVisible();
});
npx playwright test
Running 4 tests using 1 worker

  ✘  1 [chromium] › tests/flaky.spec.ts:16:1 › ❌ count() read once (1.8s)
  ✘  2 [chromium] › tests/flaky.spec.ts:21:1 › ❌ isVisible() read once (1.8s)
  ✓  3 [chromium] › tests/flaky.spec.ts:26:1 › ✅ toHaveCount retries (2.6s)
  ✓  4 [chromium] › tests/flaky.spec.ts:31:1 › ✅ toBeVisible retries (2.5s)


  1) [chromium] › tests/flaky.spec.ts:16:1 › ❌ count() read once ───────────────────────────────────

    Error: expect(received).toBe(expected) // Object.is equality

    Expected: 2
    Received: 8

      16 | test("❌ count() read once", async ({ page }) => {
      17 |   await page.getByLabel("Search products").fill("mouse");
    > 18 |   expect(await page.getByRole("listitem").count()).toBe(2);
         |                                                    ^
      19 | });
      20 |
      21 | test("❌ isVisible() read once", async ({ page }) => {
        at <project>/tests/flaky.spec.ts:18:52

    Error Context: test-results/flaky-❌-count-read-once-chromium/error-context.md

  2) [chromium] › tests/flaky.spec.ts:21:1 › ❌ isVisible() read once ───────────────────────────────

    Error: expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: false

      21 | test("❌ isVisible() read once", async ({ page }) => {
      22 |   await page.getByLabel("Search products").fill("lamp");
    > 23 |   expect(await page.getByText("No products match “lamp”.").isVisible()).toBe(true);
         |                                                                         ^
      24 | });
      25 |
      26 | test("✅ toHaveCount retries", async ({ page }) => {
        at <project>/tests/flaky.spec.ts:23:73

    Error Context: test-results/flaky-❌-isVisible-read-once-chromium/error-context.md

  2 failed
    [chromium] › tests/flaky.spec.ts:16:1 › ❌ count() read once ────────────────────────────────────
    [chromium] › tests/flaky.spec.ts:21:1 › ❌ isVisible() read once ────────────────────────────────
  2 passed (9.6s)
What’s happening
  1. beforeEach signs in and waits for all 8 products, so every test starts from a loaded shop.
  2. count() read once. fill("mouse") returns as soon as the text is in the box. The shop hasn't filtered yet (it waits 0.3 s), so count() returns 8 and expect(8).toBe(2) fails instantly. Notice the error: "Expected: 2, Received: 8" with no locator and no call log, because plain expect only ever saw the number 8.
  3. isVisible() read once. Same race: the "No products match" message doesn't exist yet when isVisible() asks, so it returns false and expect(false).toBe(true) fails.
  4. The fixed versions pass. toHaveCount(2) and toBeVisible() keep checking until the shop has filtered, about 0.3 seconds later.
  5. If the shop's search applied in 5 ms instead of 300, the bad versions would pass most of the time and fail occasionally. That's the flaky version of the same bug, and it's worse: it passes code review, then wastes hours in CI. The habit that prevents it is mechanical: never write expect(await for something on the page.
AdvancedCatching the mistake automatically
  • Lint for it. eslint-plugin-playwright has rules for this family of mistakes (such as preferring web-first assertions and flagging missing await on expect). This page didn't run it, so check its current rule names in its README before adding them to CI.
  • A missing await is the cousin of this bug: expect(locator).toHaveText("…") without await starts an assertion and moves on, so the test can end before it fails. TypeScript's @typescript-eslint/no-floating-promises catches it.
  • Screenshots compare the page too, and also retry until two shots match: toHaveScreenshot is Chapter 10.
Spot the flaky line

Which of these lines can flake, and what would you write instead? (a) expect(await page.getByTestId("cart-total").textContent()).toBe("$59.00") (b) expect(response.status()).toBe(200) (c) expect(await page.title()).toBe("Cart · Practice Shop")

Show answer

(a) and (c) can flake; (b) is fine. Write await expect(page.getByTestId("cart-total")).toHaveText("$59.00") and await expect(page).toHaveTitle("Cart · Practice Shop").

What’s happening
  1. (a) reads the total once. If the cart is still re-rendering, it gets the old total.
  2. (b) checks a response the test already has: a status code never changes after the fact, so a plain expect is correct.
  3. (c) reads the title once, and titles often change after navigation or when a page loads data (the shop's order page sets its title from the order). toHaveTitle retries.

#Your turn: assert like you mean it

Added
Your turn: fix the flaky test

This test fails on the shop. Rewrite the assertions so it passes reliably, without adding any waits:

await page.getByLabel("Search products").fill("phone"); expect(await page.getByRole("listitem").count()).toBe(2); await page.getByRole("button", { name: "Add to cart" }).first().click(); expect(await page.getByRole("link", { name: /Cart/ }).textContent()).toBe("Cart (1)");

Show answer

The answer keeps the original too, marked with test.fail(), which tells Playwright the test is expected to fail: the run reports a problem only if it unexpectedly passes. It's a handy way to prove a bad version really is bad.

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

async function signIn(page: Page, path = "/practice/shop") {
  await page.goto(path);
  await page.getByLabel("Username").fill("ana");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page).toHaveURL(path);
}

test("the original, which reads values once", async ({ page }) => {
  test.fail(); // expected to fail
  await signIn(page);
  await page.getByLabel("Search products").fill("phone");
  expect(await page.getByRole("listitem").count()).toBe(2);
  await page.getByRole("button", { name: "Add to cart" }).first().click();
  expect(await page.getByRole("link", { name: /Cart/ }).textContent()).toBe("Cart (1)");
});

test("searching for phone and adding the first result", async ({ page }) => {
  await signIn(page);
  const products = page.getByRole("list", { name: "Products" }).getByRole("listitem");

  await page.getByLabel("Search products").fill("phone");
  await expect(products.getByRole("heading")).toHaveText(["Noise-Cancelling Headphones", "USB Microphone"]);

  await products.first().getByRole("button", { name: "Add to cart" }).click();
  await expect(page.getByRole("link", { name: /Cart/ })).toHaveText("Cart (1)");
  await expect(page.getByRole("status").filter({ hasText: "Added" })).toHaveText("Added Noise-Cancelling Headphones to your cart");
});
npx playwright test
Running 2 tests using 1 worker

  ✘  1 [chromium] › tests/fix-flaky.spec.ts:11:1 › the original, which reads values once (967ms)
  ✓  2 [chromium] › tests/fix-flaky.spec.ts:20:1 › searching for phone and adding the first result (1.7s)

  2 passed (3.1s)
What’s happening
  1. The original fails at its first expect: right after signing in, the products are still loading, and even once they arrive the search applies 0.3 s later. count() reads whatever is there at that instant, and it's never 2. test.fail() turns that failure into the expected result: the list shows it with a ✘, but the summary counts it among the "2 passed".
  2. The fix replaces the count with one web-first assertion on the headings, which checks there are exactly two results and which two, waiting for both the products and the search.
  3. The original's getByRole("button", { name: "Add to cart" }).first() would click the first button on the page, whatever it is; chaining from products.first() makes it clear it's the first search result.
  4. toHaveText("Cart (1)") retries instead of reading once, and the toast check proves the right product was added: the headphones.
Your turn: poll the saved wishlist

On the account page, move "Standing Desk Mat" up once with its button, then use expect.poll to check the order the shop saved in localStorage (key shop-wishlist, a JSON array of names).

Show answer
tests/wishlist-poll.spec.ts
import { test, expect, type Page } from "@playwright/test";

async function signIn(page: Page, path = "/practice/shop") {
  await page.goto(path);
  await page.getByLabel("Username").fill("ana");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page).toHaveURL(path);
}

test("moving an item up saves the new order", async ({ page }) => {
  await signIn(page, "/practice/account");
  await page.getByRole("button", { name: "Move Standing Desk Mat up" }).click();

  await expect
    .poll(() => page.evaluate(() => JSON.parse(localStorage.getItem("shop-wishlist") ?? "null")))
    .toEqual(["Monitor Light Bar", "Standing Desk Mat", "USB Microphone"]);
  await expect(page.getByRole("list", { name: "Wishlist" }).getByRole("listitem")).toHaveText([/Monitor/, /Standing/, /USB/]);
});
npx playwright test
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/wishlist-poll.spec.ts:11:1 › moving an item up saves the new order (1.0s)

  1 passed (1.4s)
What’s happening
  1. Before the move, nothing is saved: the shop only writes shop-wishlist when the order changes, so the key is missing and the function returns null (hence the ?? "null").
  2. After "Move Standing Desk Mat up", the shop saves the new order. expect.poll keeps calling the function until the array equals the expected order, and toEqual compares arrays element by element.
  3. The last assertion checks the same order on screen. Storage and screen agreeing is the real proof: either alone could be right while the other is wrong.
Your turn: a soft checklist for the confirmation page

Place an order for one Compact Keyboard with Express delivery and check four facts on the confirmation page with soft assertions, each with a custom message: the heading, the order number, the total ($68.99) and that the delivery estimate is shown. All four should pass.

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

async function signIn(page: Page, path = "/practice/shop") {
  await page.goto(path);
  await page.getByLabel("Username").fill("ana");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page).toHaveURL(path);
}

test("the confirmation page shows everything about the order", async ({ page }) => {
  await signIn(page);
  await page.getByRole("listitem").filter({ hasText: "Compact Keyboard" }).getByRole("button", { name: "Add to cart" }).click();
  await page.goto("/practice/checkout");
  await page.getByLabel("Email").fill("ana@example.com");
  await page.getByLabel("Delivery address").fill("4 Queen Street, Toronto");
  await page.getByLabel("Express").check();
  await page.getByLabel("I agree to the terms").check();
  await page.getByRole("button", { name: "Place order" }).click();
  await expect(page).toHaveURL(/\/practice\/order\?id=ORD-1001$/); // a gate: nothing below makes sense without it

  await expect.soft(page.getByRole("heading", { level: 1 }), "thanks the customer by first name").toHaveText("Thank you, Ana!");
  await expect.soft(page.getByText("Your order ORD-1001 is confirmed."), "shows the order number").toBeVisible();
  await expect.soft(page.getByText("Total paid on delivery: $68.99"), "charges the keyboard plus express delivery").toBeVisible();
  await expect.soft(page.getByTestId("delivery-estimate"), "estimates a delivery date").toHaveText(/^Estimated delivery: \w+day, \w+ \d+$/);
});
npx playwright test
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/confirmation.spec.ts:11:1 › the confirmation page shows everything about the order (3.2s)

  1 passed (3.6s)
What’s happening
  1. The arrange part places the order: one Compact Keyboard ($59.00) with Express ($9.99), so the total should be $68.99.
  2. The URL check is a normal assertion on purpose: if the order wasn't placed, the four checks below would all fail for the same reason, so it's a gate before the checklist.
  3. The four soft assertions are independent facts about the same screen. If two were wrong, one run would report both, each under its own message.
  4. The delivery date depends on today's date, so the test matches its shape with a regex ("Thursday, November 26" style) rather than an exact date. Chapter 11's clock API makes the exact date testable.

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.