Browser tests

Wait for observable state

Use Playwright actionability and web-first assertions instead of arbitrary sleeps and race-prone immediate checks.

8 minute lesson

~~~

A fixed delay is simultaneously too slow on a fast run and too short on a slow run.

Playwright waits before actions and retries async assertions until their condition is met or the timeout expires. Wait for the UI state the user needs, such as a saved book appearing or a button becoming enabled.

await page.getByRole('button', { name: 'Add book' }).click()

const list = page.getByRole('list', { name: 'Books' })
await expect(list.getByRole('listitem')).toContainText('Dune')

Before the click, Playwright checks that the locator resolves to one element and that the element is visible, stable, enabled, and able to receive the action. After the click, the web-first assertion repeatedly reads the current page until the expected state appears or the timeout expires. Keeping the locator itself in the assertion is important; reading text once and asserting the resulting string removes that retry behavior.

Wait for the consequence that matters to the user. If saving a book should add a list item, the list item is better evidence than merely waiting for the POST response. A 200 response can still be followed by broken rendering. Wait for a response when the response itself is the contract or when it provides necessary diagnostic evidence, not as a substitute for the visible outcome.

Avoid waitForTimeout() and forced actions as routine fixes. They can hide an overlay, disabled control, or missing state transition. When an assertion times out, inspect which condition never became true and whether the application exposed a stable observable state.

Remove every explicit timeout from one test and replace it with locators and assertions about visible state. Slow the API response locally and confirm the test still passes, then prevent the UI update and confirm the assertion fails with evidence about the missing state.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →