Playwright auto-waiting: how to fix flaky tests
A flaky test passes on your machine and fails in CI, or passes nine times and fails the tenth. Almost always, the test and the page disagree about timing: the test acts or reads before the page is ready.
Playwright already waits for most things. This guide explains what it waits for, where it can't help you, and the tools for the remaining cases. Then run your tests 20 times in a row to prove they're fixed.
What Playwright waits for before an action
Before click(), Playwright waits until the element is visible, stable (not animating), enabled and not covered by another element. It also scrolls the element into view. fill() also waits for the field to be editable. These are the actionability checks.
// No wait needed: click() waits for the button to become enabled
await page.getByRole('button', { name: 'Submit order' }).click();When a check never passes, the action times out and the error names the check, for example "element is not enabled" or "another element would receive the click". That message is usually the fastest route to the cause.
click({ force: true }) skips the checks. It makes a failing click go through, which often hides a real bug: a user couldn't have clicked there either. Use it only when you can explain why the check is wrong.
- ActionabilityIntermediateClick through overlays and animations, and see what force: true hides.
- Reading FailuresBeginnerRead the call log of a click that waits, and fix the test.
Web-first assertions retry
await expect(locator).toHaveText('Passed') checks again and again until the text matches or the timeout runs out (5 seconds by default). Reading the value yourself checks it once:
// Flaky: reads the status once, maybe while it still says "Running"
expect(await page.getByTestId('status').textContent()).toBe('Passed');
// Reliable: retries until it says "Passed"
await expect(page.getByTestId('status')).toHaveText('Passed');The same applies to isVisible(), inputValue() and getAttribute(). They return the current value right away. For checks, use toBeVisible(), toHaveValue() and toHaveAttribute(), which retry. Read values only when you need them in your test, such as an order number, and only after an assertion has shown they're final.
toBeHidden() passes both for a hidden element and for one that was removed. To tell them apart, use toBeAttached() or toHaveCount(0).
- Changing TextBeginnerAssert a status that changes from Queued to Running to Passed.
- Appear & DisappearBeginnerSpinners, toasts and late elements, without a single sleep.
Timeouts, not sleeps
page.waitForTimeout(3000) is the most common cause of slow and flaky suites at once. It waits too long when the app is fast and not long enough when CI is slow. If something takes longer than the default 5 seconds, raise the timeout of that one assertion:
await page.getByRole('button', { name: 'Load slowly' }).click();
await expect(page.getByTestId('slow-element')).toBeVisible({ timeout: 10_000 });The assertion still finishes as soon as the text appears. The timeout is only the upper limit. For everything that depends on time itself, such as countdowns, session expiry or "sale on weekends", don't wait at all: install a fake clock with page.clock and fast-forward it.
- Appear & DisappearBeginnerAn element that takes 7 seconds, longer than the default timeout.
- Timers & ClockAdvancedFast-forward a two-minute countdown in milliseconds.
Wait for the response, not for the screen
After a click that loads data, the old content often stays on screen until the new data arrives. A test that reads the rows right after clicking Next reads the old page. Wait for something that only changes once the data is in, such as the page indicator, or wait for the response itself.
// Start waiting before the click, so the response can't arrive first
const responsePromise = page.waitForResponse('**/api/status/200');
await page.getByRole('button', { name: 'Quick save' }).click();
const response = await responsePromise;
expect(response.ok()).toBe(true);The order matters. If you call waitForResponse() after the click, a fast response can arrive in between, and the test waits for a response that already came.
expect.poll and toPass for everything else
Some conditions aren't about one element. A progress value crossing 70%, an API that eventually returns "Shipped", a file appearing. expect.poll() runs a function until its result passes the assertion:
await expect
.poll(async () => {
const response = await request.get('/api/orders/1042');
return (await response.json()).status;
}, { timeout: 30_000 })
.toBe('Shipped');expect(async () => { ... }).toPass() retries a whole block, actions included, until every assertion in it passes. It's powerful but easy to misuse: retrying a click can hide a real bug, such as a button that only works on the second try.
- Progress BarIntermediatePoll aria-valuenow and stop the bar at the right moment.
- Flaky LabAdvancedUse toPass() and decide when it is the right tool.
Things that appear at random
A cookie banner or newsletter popup that shows up at a random moment can cover the button your test is about to click. Wrapping every click in "close the popup if it's there" is slow and still racy. page.addLocatorHandler() runs your handler whenever the overlay blocks an action, then retries the action:
await page.addLocatorHandler(
page.getByRole('dialog', { name: 'Join our newsletter' }),
async (dialog) => {
await dialog.getByRole('button', { name: 'No thanks' }).click();
},
);- Modals & OverlaysIntermediateA newsletter popup that interrupts at a random moment.
Prove it is fixed
A flaky test that passed once proves nothing. Run it many times, with as many workers as CI uses:
npx playwright test flaky.spec.ts --repeat-each=20 --workers=4When it still fails, record a trace with --trace on and open the failing run. The trace shows the page before and after each action, the network requests and the console, which usually shows what wasn't ready yet.
- Flaky LabAdvancedMake three flaky tests pass 20 times in a row.
- Trace ViewerIntermediateFind a timing bug with the Trace Viewer instead of guesswork.
Exercises in this guide
- ActionabilityIntermediate
- Changing TextBeginner
- Appear & DisappearBeginner
- Timers & ClockAdvanced
- Data GridAdvanced
- Flaky LabAdvanced
- Progress BarIntermediate
- Modals & OverlaysIntermediate
- Reading FailuresBeginner
- Trace ViewerIntermediate
More guides
- Playwright practice for beginners: a four-week plan
- Playwright locators: a practical guide with exercises
- Testing iframes with Playwright
- Playwright network mocking and API testing
- Playwright authentication: sign in once with storageState
- Playwright Page Object Model with fixtures
- File upload and download in Playwright
- Playwright Trace Viewer: how to debug failing tests
- Running Playwright tests in CI with GitHub Actions
- Playwright cheat sheet: locators, actions and assertions