What is expect.poll in Playwright?
Written by Jatin Thacker, Automation Architect · Updated
This answer is one piece of Chapter 11: Assertions.
- Web-First Assertions Cookbook
- Retry & Polling Patterns
- Visual Regression Testing
- Making a Failure Explain Itself
Web-first assertions retry, but only for locators and the page. Sometimes the thing you want to check is a plain value: a count from an API, a setting in localStorage, a number your code works out. A one-off expect(value).toEqual(...) reads it once, so it fails if the app has not finished writing.
expect.poll() fixes that. You pass a function that returns the value, which may be async. Playwright calls it, applies the matcher, and if it fails, waits and calls it again. By default it waits 100, 250, 500 and then 1000 milliseconds between attempts, and gives up after 5 seconds. Both can be changed with intervals and timeout.
In the example, clicking Add to cart saves the cart to localStorage under meridian.cart. The polled function reads it with page.evaluate() and returns the list of SKUs. The matcher toEqual(['MRD-1003']) retries until the grinder's SKU is saved.
Keep the function free of side effects: it may run several times. To retry a block that performs actions, use toPass().
import { test, expect } from '@playwright/test';
test('the cart is saved to localStorage', async ({ page }) => {
await page.goto('/catalog.html?mock=static&seed=42&autologin=1');
await page.locator('article[data-sku="MRD-1003"]')
.getByRole('button', { name: 'Add to cart' }).click();
await expect.poll(async () => {
const cart = await page.evaluate(() => JSON.parse(localStorage.getItem('meridian.cart') || '[]'));
return cart.map((line) => line.sku);
}).toEqual(['MRD-1003']);
});1 passed (2.2s)
page.evaluate(() => localStorage.length). Which tool fits?Practised in the full course: the drill Actionability: Polling.
See the chapterRelated questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free