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

Playwright › Auto-waiting and web-first assertions

expect.poll and toPass: retries for your own logic

A value that does not come from a locator, such as a status in an API or database, is re-read with expect.poll. It calls a function that returns the value and applies the matcher to each result until it matches. toPass repeats a whole block of steps and assertions. The default timeout of toPass is 0, so it is set explicitly, and only idempotent actions go into the block.

Playwright · Waiting

An order status changes on the backend within seconds, but the UI never shows it. What do you wait for?

After payment the page says "Thank you", but the order becomes PAID only once the backend has processed the payment: a second, sometimes ten. There is no locator to hang toHaveText on: the status lives in an API or a database. The typical "fix" is waitForTimeout(5000) and one request after it. It is either needlessly slow or, in a loaded environment, still not enough. This lesson covers two tools that repeat a check where a web-first assertion does not apply: expect.poll and toPass.

How it works and why. A web-first assertion retries because it knows what to repeat: re-read the element by its locator. A plain expect(value) receives a ready value, so there is nothing to repeat. Playwright offers two ways to bring re-reading back. expect.poll takes a function that returns a value and calls it again and again, applying a matcher to each result. toPass takes a block of code with assertions and repeats it whole until the block finishes without an error. Both have a timeout and a list of intervals between attempts, so the app is not hammered in a tight loop.

expect.poll: polling a value. The function only has to return the current value; the matcher does the assertion:

import { test, expect } from '@playwright/test';

test('order becomes PAID after payment', async ({ page, request }) => {
  await page.goto('/checkout');
  await page.getByRole('button', { name: 'Pay' }).click();
  const id = await page.getByTestId('order-id').innerText();

  await expect
    .poll(
      async () => {
        const res = await request.get('/api/orders/' + id);
        return (await res.json()).status;
      },
      {
        message: 'the order must become PAID',
        timeout: 30_000,
        intervals: [500, 1000, 2000],
      },
    )
    .toBe('PAID');
});

Without intervals the pauses between attempts grow: 100, 250, 500, 1000 ms, then stay at 1000. Without timeout the value of expect.timeout (5 seconds) is used, so for slow processing you set it explicitly. Ordinary matchers are supported (toBe, toEqual, toBeGreaterThan, toContain, not), but locator matchers such as toBeVisible are not, because the value is no longer an element. When time runs out, message becomes part of the error message.

toPass: repeating a whole block. When a check needs several steps, for example "reload the page and look at a row in a table", a function returning a value does not fit. Then you repeat the block:

await expect(async () => {
  await page.reload();
  await expect(page.getByRole('row', { name: 'Report 42' })).toContainText('Ready', {
    timeout: 1000,
  });
}).toPass({ timeout: 20_000, intervals: [1000, 2000] });

A catch: toPass has a default timeout of 0, meaning it does not take expect.timeout and retries until the test's own time runs out. So always set the limit. Give the inner assertions short timeouts too: otherwise one iteration can take 5 seconds, and in 20 seconds you get only a few attempts.

Web-first assertionexpect.polltoPass
What is repeatedThe locator checkA call of a function that returns a valueThe whole block of actions and assertions
When to useUI stateAPI, DB, file, any valueA sequence of actions that must be repeated
Default timeout5 s (expect.timeout)5 s (expect.timeout)0, i.e. until the test ends

Example: from a pause to poll. The original waits blindly:

// before
await page.getByRole('button', { name: 'Pay' }).click();
await page.waitForTimeout(5000);
const res = await request.get('/api/orders/' + id);
expect((await res.json()).status).toBe('PAID');

When processing is fast, the test idles for 5 seconds for nothing; when it takes 6, the test fails with "Expected: PAID, Received: PENDING". Replacing it with expect.poll looks like the example above: the test finishes the moment the status becomes PAID, and the upper bound (30 seconds) shows that the wait is a deliberate limit, not a guess. If the status has not changed in 30 seconds, it is no longer a synchronisation problem but a real bug or an unavailable queue.

The danger of repeated actions. Inside toPass actions run on every attempt. Put "Pay" or any POST there and they repeat, producing a duplicate:

Where to put the action relative to toPass

Typical

Action inside toPass

Attempt 1: click, no confirmation yet, the block fails. Attempt 2: click again. Attempt 3: one more. The system holds several orders, and the test is green.

Better

Action outside toPass

The click runs once. Only the check (an assertion or a read request) repeats; it changes nothing, so any number of attempts is safe.

Figure 1. A repeated block has room only for idempotent steps: reading, refreshing, navigating.
// BAD: every iteration creates one more order
await expect(async () => {
  await page.getByRole('button', { name: 'Place order' }).click();
  await expect(page.getByText('Order created')).toBeVisible({ timeout: 1000 });
}).toPass({ timeout: 10_000 });

// GOOD: the action once, only the check repeats
await page.getByRole('button', { name: 'Place order' }).click();
await expect(page.getByText('Order created')).toBeVisible();

Limits and alternatives. Polling does not replace proper synchronisation with the UI: if the needed value is visible on the page, a web-first assertion with a locator is shorter and reads better. The function in poll must have no side effects (GET, not POST), because it is called many times. Polling loads the backend, so intervals are not made too short, and the timeout is tied to the expected processing time (for example the queue's SLA), not "with a margin". If processing takes minutes, such a test is better moved to a lower level or checked another way. Other tools do something similar with FluentWait in Selenium or a recursive cy.request in Cypress, but in Playwright repetition, intervals and messages are built in.

Common mistakes.

  • Using poll or toPass where an ordinary web-first assertion is enough: needless complexity and a worse report.
  • Not setting a toPass timeout: the test "hangs" until its own limit, and the real cause is lost.
  • Putting a non-idempotent action (payment, creation) in the block: duplicate data and a falsely green test.
  • Writing your own loop with waitForTimeout inside the poll function: retrying is already built in.
  • Intervals that are too short on a slow backend: the test creates load itself.

Check yourself

A toPass block contains a click() on "Submit" and an assertion for a success message. Why is it dangerous and how do you rewrite it?

Answer

If the assertion does not pass on the first attempt, the block repeats together with the click, so the form may be submitted several times. Move the click before toPass (or keep only the assertion, which retries by itself), and leave only reading or an idempotent refresh in the block.

Why does expect.poll(() => fetchStatus()).toBe('PAID') fail after 5 seconds although processing takes 12?

Answer

The poll timeout defaults to expect.timeout, i.e. 5 seconds. For slow processing set it in the second argument: { timeout: 30_000 }. For toPass the default is 0, so there the thing to remember is the opposite: set a limit.

In an interview. Junior: When I wait not for an element but for a value from an API, I use expect.poll: it calls a function until the value matches the expected one. Middle/Senior: To repeat a sequence of steps I use toPass and always give it a timeout, because by default it is 0 and bounded only by the test. I put only idempotent actions in the block, otherwise a retry creates duplicates. I pick intervals and the upper bound to match the real processing time, so I neither load the backend nor hide a real bug behind a long pause.

More articles in this chapter