QA Interview Hub · Knowledge base · Quizzes · Українська

Playwright › Auto-waiting and web-first assertions

Web-first assertions

Web-first assertions check a condition in a loop until it holds or the assertion timeout (5 seconds) runs out. On every attempt the locator finds the element again and compares its state, which makes them more reliable than waitForTimeout. Only matchers on a locator or page retry; toBe over a value taken from textContent() or count() reads once and waits for nothing.

Playwright · Waiting

The message shows up after 300 ms, yet the test is already red. Add waitForTimeout?

A test clicks "Save" and reads the status text right away. Sometimes the "Saved" message is not there yet, the test fails, and the nearest fix is waitForTimeout(1000) before the check. A month later the suite has dozens of pauses, a run is slow, and flaky failures still happen. This lesson is about why waiting built into the assertion beats any pause, how it works, and where it stops helping.

How it works and why. Web-first assertions are expect calls that receive a locator or a page: toBeVisible, toHaveText, toHaveValue, toHaveCount, toHaveURL and others. They do not compare a value that already sits in a variable: they check a condition in a loop. On every attempt the locator finds the element again (a locator is lazy and only stores a description of how to search), reads its state and compares it with the expected one. A match ends the assertion at once. No match: a short pause and a new attempt, until the assertion timeout runs out.

This design solves the main problem: nobody knows in advance when the UI will "catch up". A fixed pause is always either too long (slow run) or too short (unstable test). The loop runs exactly as long as needed: a fast app passes in milliseconds, a slow one gets headroom up to the timeout.

One read versus a repeated check

text appears textContent() + toBeFAILone read toHaveTextOKretries until it matches
Figure 1. Each circle is one read of the element. A plain toBe reads once; a web-first assertion keeps reading until it matches or the timeout ends.

The assertion timeout defaults to 5 seconds. It is a separate limit, not to be confused with the test timeout (30 seconds). Change it in the config via expect.timeout or for a single call with the timeout option. await always precedes expect, because the assertion returns a promise.

// playwright.config.ts
export default defineConfig({
  expect: { timeout: 10_000 },   // for all web-first assertions
});

// in a test
await expect(page.getByRole('status')).toHaveText('Done');
await expect(page.getByRole('alert')).toBeVisible({ timeout: 15_000 });
await expect(page.getByRole('dialog')).not.toBeVisible();
await expect(page).toHaveURL(/\/orders\/\d+$/);

Example: from a falsely red test to a stable one. The original version reads the text once:

// before
await page.getByRole('button', { name: 'Save' }).click();
const msg = await page.getByRole('status').textContent();
expect(msg).toBe('Saved');

textContent() waits only for the element to appear in the DOM, not for the expected text: it returns the value "right now", and if the request is still in flight, msg holds an empty string. After that a plain toBe compares two strings and has nothing to retry. The error looks like this (shortened; exact wording depends on the version):

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

Expected: "Saved"
Received: ""

There is not a word about a timeout in it: a sign that nothing was retried. The fix changes not the "length of the wait" but the kind of check:

// after
await page.getByRole('button', { name: 'Save' }).click();
await expect(page.getByRole('status')).toHaveText('Saved');

Now a failure, if it happens, looks different, and it shows what Playwright actually saw (also shortened):

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

Locator: getByRole('status')
Expected: "Saved"
Received: ""
Timeout: 5000ms

There is a Locator and a Timeout, and Received shows the last observed value. If it is still empty after 5 seconds, the problem is not synchronisation but the app: the message really did not appear.

What replaces what. Every method that returns a value "right now" has a web-first counterpart:

Reads onceRetries until the timeout
expect(await el.isVisible()).toBe(true)await expect(el).toBeVisible()
expect(await el.textContent()).toBe('Ok')await expect(el).toHaveText('Ok')
expect(await el.inputValue()).toBe('42')await expect(el).toHaveValue('42')
expect(await el.count()).toBe(3)await expect(el).toHaveCount(3)
expect(page.url()).toContain('/orders')await expect(page).toHaveURL(/orders/)

The difference is subtle: toHaveText('Ok') compares the whole text (whitespace is normalised), while toContainText('Ok') looks for a substring. For a list, pass an array: toHaveText(['Apple', 'Pear']) waits for the same number of elements with texts matching in order.

Disappearing and absence. Negative checks retry too. await expect(spinner).toBeHidden() waits until the element becomes invisible or leaves the DOM, and not.toBeVisible() behaves the same. To tell "in the DOM but hidden" from "not in the DOM", use toBeAttached() and not.toBeAttached(). A typical loader pattern: first wait for the spinner to go away, only then check the data.

Limits. Only matchers that work with a locator or a page retry. General toBe, toEqual, toContain compare a ready value and wait for nothing. The same goes for isVisible(), textContent(), count(): they answer "what is now", and Playwright explicitly advises against building checks on them. If the value does not come from a locator (an API response, a file), you need expect.poll or toPass: the topic of a separate lesson. One more limit: an assertion waits only up to its own timeout; if the app really answers in 20 seconds you can raise the limit, but first find out why it is so slow.

Comparison with other tools. In Cypress, should commands retry automatically too, the idea is the same. Selenium has nothing like this out of the box: you write a WebDriverWait with a condition, and it is easy to forget or to wrap in the wrong place. So Playwright's "waits by itself" applies to assertions, not to arbitrary JavaScript around them.

Common mistakes.

  • Forgetting await before expect(locator): the test may end before the check does, and the error shows up later or gets lost.
  • Taking values via textContent(), isVisible(), count() and comparing them with a plain toBe: the check reads once and is unstable.
  • Raising expect.timeout to 30 seconds "so it stops failing": a slow app is not cured, and a real defect (the message never appears) is found half a minute later.
  • Putting waitForTimeout before an assertion: the pause adds no reliability, and the run gets slower with every use.
  • Checking the spinner is gone via isVisible() right after a click: the spinner has not appeared yet, so the check passes by mistake.

Check yourself

A product list loads from an API. The test does expect(await page.getByRole('listitem').count()).toBe(5) and fails with "Received: 0", although the app shows 5 products. What is the cause and what should change?

Answer

count() returned a number at a moment when the API response had not arrived yet, and toBe retries nothing. Replace the check with await expect(page.getByRole('listitem')).toHaveCount(5): then the count is re-read until it becomes 5 or the timeout ends.

The assertion expect(page.getByRole('alert')).toBeVisible() without await is the last line of a test, and there is no banner. Why can the test be green?

Answer

Without await the test does not wait for the assertion's promise and finishes before the check can fail. At best the error surfaces later as an unhandled rejection, at worst nothing is verified. That is why await is mandatory, and the linter rule no-floating-promises helps not to forget it.

In an interview. Junior: For checks I use web-first assertions with a locator, such as toHaveText: they retry the check up to the timeout themselves, so no pauses are needed. Values taken via textContent() or isVisible() do not retry. Middle/Senior: The assertion re-reads the element on each attempt because the locator is lazy, and it has its own timeout (5 s), separate from the test timeout. So toBe over a value taken once is unstable, and waitForTimeout only hides the problem. If what I wait for is not UI but an API or a file, I switch to expect.poll or toPass.

More articles in this chapter