#Web-first assertions retry
AddedAn 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.
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 });
});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)- The toast. After the click,
toHaveTextkeeps reading the status region until it says "Added Wireless Mouse to your cart". ThentoBeHiddenkeeps 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. - Values you already have.
toHaveCount(8)waits for the products. Only then does the test read every price once withallTextContents()and turn them into numbers. From here on they're plain values, nothing is going to change them, soexpect(…).toBe(29.5)checking once is exactly right. - 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
timeoutpassed to it) and then fails. - 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>" withunexpected 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.
- For the whole project:
expect: { timeout: 10_000 }inplaywright.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 anexpectwith 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.