Why do async UI assertions flake, and what replaces sleep?
Question
Clicking Save sends PATCH /profile, shows Saving... inside <div role="status">, and changes it to Saved when the server replies (80 ms locally, 400 ms in CI, 2,300 ms during CI spikes). On HTTP 500, it renders <div role="alert">Save failed</div>.
A colleague tried to fix a flaking test by adding waitForTimeout(2000):
await page.locator('.btn-primary >> nth=1').click();
await page.waitForTimeout(2000);
const text = await page.locator('div.card > div > span').textContent();
expect(text).toBe('Saved');- Why did the raw
textContent()check flake, and why iswaitForTimeout(2000)still broken? - Rewrite the locators and assertions reliably.
- How do you test both
Saving...and the HTTP 500 error without timing races?
Show hints (3)
- "SNAPSHOT VERSUS RETRY"
textContent()reads the DOM once at that exact millisecond. What doesawait expect(locator).toHaveText('Saved')do instead? - "LOCATE LIKE USERS"
Replace positional CSS (
nth=1,div.card > div > span) with accessible queries likegetByRole('button', { name: 'Save' })andgetByRole('status'). - "CONTROL THE NETWORK"
Hold
PATCH /profileopen withpage.routeto assertSaving...deterministically, then fulfill it with200or500.
Show checked explanation
textContent() snapshots the DOM once before PATCH /profile finishes, and waitForTimeout(2000) wastes 1,920 ms locally while still failing on a 2,300 ms CI spike. Replace brittle CSS with accessible role/label locators, use auto-retrying web-first assertions (await expect(locator).toHaveText('Saved')), and intercept the request with page.route to test Saving... and HTTP 500 reliably.
Parsed and executed both JavaScript snippets and the Testing Library waitFor pattern against mock harnesses on Node.js v24.15.0 (including pre-route release ordering) and simulated 80 ms, 400 ms, 2,300 ms, and HTTP 500 timelines on CPython 3.12.10. Checked by an editor other than the author.
Walkthrough
Three bugs hide in those four lines: a one-shot DOM snapshot (textContent() + toBe), a hardcoded 2,000 ms sleep, and brittle CSS selectors (.btn-primary >> nth=1 and div.card > div > span) that break whenever markup changes.
| Strategy | Local (80 ms) | CI (400 ms) | CI spike (2,300 ms) | Verdict |
|---|---|---|---|---|
Instant textContent() | Fails at 0 ms | Fails at 0 ms | Fails at 0 ms | Races every network call |
waitForTimeout(2000) | Wastes 1,920 ms | Wastes 1,600 ms | Fails at 2,000 ms | Slow and still flaky |
Web-first toHaveText (5 s) | Passes in ~80 ms | Passes in ~400 ms | Passes in ~2,300 ms | Fast and deterministic |
1. Locate like a user. Query by accessibility role and label first (getByRole, getByLabel), falling back to getByTestId only when no semantic hook exists. That decouples tests from styling refactors and catches broken labels.
2. Use web-first auto-retrying assertions. await expect(locator).toHaveText('Saved') (Playwright default timeout: 5,000 ms) re-queries the live DOM until the text matches or times out. In Testing Library, bare findByRole('status') resolves too early on Saving.... Use await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('Saved')), or await screen.findByText('Saved') when new text appears.
3. Gate the network to test transient states. Fast servers finish before a test can catch Saving.... Create the gate promise before page.route so release() is always defined, assert the loading UI, then release 200 (or 500 for role="alert"):
let release;
const gate = new Promise((r) => { release = r; });
await page.route('**/profile', async (route) => {
await gate;
await route.fulfill({ status: 200, json: { ok: true } });
});
await page.getByLabel('Display name').fill('Ada');
await page.getByRole('button', { name: 'Save' }).click();
await expect(page.getByRole('status')).toHaveText('Saving...');
release();
await expect(page.getByRole('status')).toHaveText('Saved');For the failure path, fulfill with status: 500 and assert await expect(page.getByRole('alert')).toHaveText('Save failed') plus that the Save button re-enables for retry.
Common mistakes
- Writing
expect(await locator.isVisible()).toBe(true). CallingisVisible()first returns a plain boolean once and disables Playwright's auto-retry. - Waiting for
networkidleas a universal sync hook. Background analytics, WebSockets, or polling keepnetworkidlepending or fire too early before React commits the DOM. - Adding
click({ force: true })to silence actionability timeouts. That clicks through disabled buttons or blocking modals and hides real user bugs. - Asserting
Saving...against a live unthrottled backend. When the server replies in 20 ms, the loading badge vanishes before the check runs.
Follow-up questions
- "How do you assert that a loading spinner has disappeared without racing?" In Playwright, use
await expect(page.getByRole('progressbar')).toBeHidden(), which retries until the node is hidden or detached. In Testing Library, wrapqueryByRole('progressbar')insideawait waitFor(() => expect(...).not.toBeInTheDocument())(orwaitForElementToBeRemoved). - "What if two buttons on the page share the visible label
Save?" Playwright's strict mode fails on ambiguous locators instead of clicking the wrong one. Scope by container landmark or section (page.getByRole('region', { name: 'Profile' }).getByRole('button', { name: 'Save' })), rather than reaching fornth=1. - "If you stub
PATCH /profilewithpage.route, how do you still catch real backend bugs?" Usepage.routefor UI state-machine tests (loading, 500, timeout, slow replies). Keep a smaller set of unstubbed end-to-end smoke checks plus API contract tests to cover the real server.
What a strong answer covers
Explains why one-shot snapshots and waitForTimeout(2000) fail, switches to accessible role/label locators and auto-retrying web-first assertions, and gates PATCH /profile with page.route to test Saving..., Saved, and HTTP 500 cleanly.
Open in interactive practice deck →