日本語

How to Wait for a Value That Doesn’t Change Right Away in Playwright

​​Playwright​E2E Testing,TypeScript

With Playwright's expect.poll() and toPass(), you can keep re-fetching and wait until a condition is met, even for values that are not screen elements. Auto-waiting assertions such as toHaveText() check screen elements and similar things, and cannot be used with values returned by a function. These two call the function that gets the value again and again. Use them when you want an E2E test to confirm that an asynchronous process has finished, for example: "Pressing a button starts a background job, and a little later the API's status becomes done."

In a test environment, I built an API whose status changes from running to done a little while after the job starts. I measured at which millisecond the value was re-fetched and where the waiting stopped.

Note

The test environment is Ubuntu 24.04, Node.js 22.23.4, and @playwright/test 1.63.0. I wrote the tests in TypeScript, ran them only in headless Chromium, and used a single worker. The API was a server written with Node.js's http module, started on 127.0.0.1:3000 through webServer in the config file. I did not test external services' APIs, Firefox and WebKit, Playwright in other languages such as Python, or running on CI services.

Comparing the value once is not enough: it is still running

The test server creates one job with POST /jobs?doneAfter=1800 and returns its id. Until doneAfter milliseconds have passed since the job was created, GET /jobs/:id returns {"status":"running","items":0}. After that, it returns {"status":"done","items":3}. From the test, I create a job with the following createJob().

ts
// tests/helpers.ts (partial)
import type { APIRequestContext } from '@playwright/test';

export async function createJob(request: APIRequestContext, doneAfter: number) {
  const res = await request.post(`/jobs?doneAfter=${doneAfter}`);
  return (await res.json()).id as string;
}

First, I compared the fetched value once with toBe().

ts
// tests/no-wait.spec.ts
import { test, expect } from '@playwright/test';
import { createJob } from './helpers';

test('1回だけ取得して比べる', async ({ request }) => {
  const id = await createJob(request, 1800);
  const job = await (await request.get(`/jobs/${id}`)).json();
  expect(job.status).toBe('done');
});

The test failed after 42ms. toBe() only compares the value passed in, once, on the spot. It does not wait.

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

    Expected: "done"
    Received: "running"

Use expect.poll to keep re-fetching until done

You pass a function that returns the value to expect.poll(). Playwright calls that function and compares the result with toBe() and similar matchers. If the condition is not met, it waits a little and calls the function again. To record the millisecond each call happens, the function calls sw.tick() (stopwatch() is a helper that just stores call times in an array).

ts
// tests/poll.spec.ts (partial)
test('expect.poll で done になるまで取り直す', async ({ request }) => {
  const id = await createJob(request, 1800);
  const sw = stopwatch();
  await expect.poll(async () => {
    sw.tick();
    const job = await (await request.get(`/jobs/${id}`)).json();
    return job.status;
  }).toBe('done');
  console.log(`[計測] 呼ばれた時刻(ms): ${sw.calls.join(', ')} / 終わるまで ${sw.elapsed()}ms`);
});

When I ran it with the job set to become done at 1800ms, the function was called 5 times, and the test passed at 1876ms.

text
[計測] 呼ばれた時刻(ms): 1, 104, 359, 863, 1872 / 終わるまで 1876ms

The intervals between call times were roughly 100ms, 250ms, 500ms, and 1000ms. According to the official expect.poll documentation, the default retry intervals are [100, 250, 500, 1000], and after the array runs out, the last value is repeated. The first check after done was at 1872ms, so most of the waiting time was spent before the done time (1800ms).

You can change the intervals with intervals. With intervals: [200], the function was called about every 200ms, 10 times in all, and the test passed at 1846ms.

ts
await expect.poll(async () => {
  // Same body as above
}, { intervals: [200] }).toBe('done');
text
[計測] 呼ばれた時刻(ms): 1, 207, 412, 616, 821, 1025, 1230, 1434, 1638, 1842 / 終わるまで 1846ms
Diagram comparing the times when expect.poll fetched the value, in two rows. With the default intervals, it was called 5 times at 1, 104, 359, 863, and 1872ms, and succeeded on the 5th call. With intervals: [200], it was called about every 200ms, 10 times, and succeeded on the 10th call at 1842ms. Both succeeded just after the done time of 1800ms
Times when expect.poll fetched the value (done happens at 1800ms)

The gap between the done time of 1800ms and the check that noticed it was 72ms with the default intervals and 42ms with [200]. However, [200] called the API twice as many times, 10 instead of 5. With the default intervals, the wait starts short and gets longer over time. The shorter the interval, the sooner the change is noticed, but the more calls are made.

The default time limit for expect.poll is 5 seconds

By default, expect.poll() gives up after 5 seconds. When I made it wait for a job that becomes done at 7000ms, it failed after 8 calls. If you pass message, that text appears at the start of the error.

ts
// tests/poll-timeout.spec.ts (partial)
await expect.poll(async () => {
  sw.tick();
  return (await (await request.get(`/jobs/${id}`)).json()).status;
}, { message: '仕事が done になる' }).toBe('done');
text
[計測] 呼ばれた回数 8 / 終わるまで 4911ms

    Error: 仕事が done になる

    仕事が done になる

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

    Expected: "done"
    Received: "running"

    Call Log:
    - Timeout 5000ms exceeded while waiting on the predicate

When I passed { timeout: 10_000 } and waited for the same job, which becomes done at 7000ms, done was returned on the 11th call, and the test passed at 7939ms. The expect: { timeout: 2000 } setting in the config file also applies to expect.poll(). With that setting and no timeout passed, a job that never finishes stopped after 5 calls at 1895ms, and the error said Timeout 2000ms exceeded.

toPass retries a whole block of processing

toPass() calls the function passed to expect() again and again until all the assertions inside it pass. The official toPass documentation describes it as retrying a block of code until it passes. Unlike expect.poll(), which returns a single value, you can write two or more assertions inside it.

ts
// tests/to-pass.spec.ts (partial)
await expect(async () => {
  sw.tick();
  const job = await (await request.get(`/jobs/${id}`)).json();
  expect(job.status).toBe('done');
  expect(job.items).toBe(3);
}).toPass();
text
[計測] 呼ばれた時刻(ms): 3, 111, 367, 873, 1880 / 終わるまで 1888ms

The call times were almost the same as with expect.poll(). The default retry intervals are also the same, [100, 250, 500, 1000].

Inside toPass(), you can also repeat page actions. I wrapped a check in toPass() for a page that fetches the API and shows either "processing" or "done" only when the "Refresh" button is pressed. Pressing "Refresh" and then checking the display is repeated inside toPass(). The display does not change unless the button is pressed, so waiting with toHaveText() alone never reaches "done".

ts
await expect(async () => {
  sw.tick();
  await page.getByRole('button', { name: '更新' }).click();
  await expect(page.locator('#status')).toHaveText('完了');
}).toPass();

With this approach, the job completed at 1500ms, but it took 5242ms before the test passed. The button was pressed only twice.

text
[計測] 押した時刻(ms): 20, 5193 / 終わるまで 5242ms

The toHaveText() inside is also an auto-waiting assertion. On the first press, the text stayed at "processing", and it waited for the full default 5-second timeout before failing. During that time, toPass() could not move on to the next retry. When I added { timeout: 500 } to the inner toHaveText(), the test ran 6 times and passed at 1535 to 2528ms. It passed on the 3rd press twice and on the 4th press four times. When I ran the inner toHaveText() with its default setting, 6 times, the results were 5231 to 5242ms.

ts
await expect(page.locator('#status')).toHaveText('完了', { timeout: 500 });
Diagram comparing the times when "Refresh" was pressed inside toPass, in two rows. With the default inner toHaveText, the button was pressed at 18ms and 5184ms, and it passed on the 2nd press. With timeout: 500, it was pressed at 15, 671, 1448, and 2472ms, and it passed on the 4th press. The job completes 1500ms after it was created
Times when "Refresh" was pressed inside toPass (first of the repeated runs; the run that passed on the 4th press)

toPass has no time limit by default

The time limit for toPass() is 0 (no limit) by default. The official documentation also states that toPass has a timeout of 0 by default and does not follow the expect timeout in the config file.

I set expect: { timeout: 2000 } in the config file and made a toPass() without timeout wait for a job that never finishes. I set the test's time limit to 10 seconds with test.setTimeout(10_000).

text
[計測] 呼ばれた回数 12 / 8942ms で止まった

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

    Expected: "done"
    Received: "running"

    Call Log:
    - Test timeout of 10000ms exceeded

With the same config, expect.poll() stopped after 2 seconds, but toPass() kept re-running until the test's time limit. The test timeout is 30 seconds by default. So if you change nothing, a toPass() that never passes keeps re-running until it reaches the test timeout (30 seconds).

To give toPass() a time limit, pass it as an argument, such as toPass({ timeout: 3000 }), or set expect.toPass.timeout in the config file.

ts
// playwright.config.ts (partial)
export default defineConfig({
  expect: { toPass: { timeout: 3000 } },
});

With this setting, a toPass() without a timeout stopped after 6 calls (at 2895ms), and the error was Timeout 3000ms exceeded while waiting on the predicate. When I passed { timeout: 3000 } as an argument, it also stopped after 6 calls at 2878ms.

Point

For screen elements, first wait with locator assertions such as toHaveText(). The official documentation also recommends using auto-waiting assertions where possible and using expect.poll() and toPass() for more complex waits. To compare a single value you fetch, use expect.poll(). To repeat button clicks or multiple assertions together, use toPass(), and always give toPass() a time limit.

​Posted by 86