Appear & Disappear
Elements that show up late, go away on their own, or leave the page in different ways.
Assertions wait for you
expect(locator).toBeVisible() does not check once. It keeps checking until the element is visible or the timeout runs out, which is 5 seconds by default. So an element that appears after 3 seconds needs no extra code:
await page.getByRole('button', { name: 'Show element' }).click();
await expect(page.getByTestId('delayed-element')).toBeVisible();Never use a fixed sleep
page.waitForTimeout(3000) either waits too long, which is slow, or not long enough, which is flaky. Wait for the state you need instead.
Slower than the timeout? Raise it for that one check
await page.getByRole('button', { name: 'Load slowly' }).click();
await expect(page.getByTestId('slow-element')).toBeVisible({ timeout: 10_000 });Waiting for something to go away
Spinners and toasts should disappear. Assert that too: toBeHidden() waits just like toBeVisible().
await page.getByRole('button', { name: 'Start loading' }).click();
await expect(page.getByTestId('loading-spinner')).toBeVisible();
await expect(page.getByTestId('loading-spinner')).toBeHidden();
await expect(page.getByTestId('loading-result')).toBeVisible();Hidden is not the same as removed
toBeHidden()passes for both: the element is invisible or not in the page at all.toBeAttached()passes only while the element is still in the DOM, even if it is invisible.toHaveCount(0)passes only when it is gone.
Delayed element
Appears 3 seconds after the click, or 7 seconds for the slow one. Clicking again restarts the wait.
Loading spinner
Shows a spinner for 3 seconds, then the result.
Toast notification
A confirmation that disappears by itself after 3 seconds.
Hidden or removed
Both elements disappear from view, in different ways. One is removed from the page; the other stays in it, hidden.
Related exercises
- Dynamic ElementsBeginnerChanging TextAssert text that changes over time or is different on every run.
- Dynamic ElementsAdvancedFlaky LabMake tests that pass every time, then prove it by running them many times.
- Network & APIIntermediateAPI PlaygroundCheck both what the UI shows and what actually went over the network.
Read the guide: Playwright auto-waiting: how to fix flaky tests