download

Why do async UI assertions flake, and what replaces sleep?

Testing~8 minReviewed 2 Dec 2026Free · No sign-in

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):

"JAVASCRIPT"
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');
  1. Why did the raw textContent() check flake, and why is waitForTimeout(2000) still broken?
  2. Rewrite the locators and assertions reliably.
  3. How do you test both Saving... and the HTTP 500 error without timing races?
Show hints (3)
  1. "SNAPSHOT VERSUS RETRY"

    textContent() reads the DOM once at that exact millisecond. What does await expect(locator).toHaveText('Saved') do instead?

  2. "LOCATE LIKE USERS"

    Replace positional CSS (nth=1, div.card > div > span) with accessible queries like getByRole('button', { name: 'Save' }) and getByRole('status').

  3. "CONTROL THE NETWORK"

    Hold PATCH /profile open with page.route to assert Saving... deterministically, then fulfill it with 200 or 500.

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.

StrategyLocal (80 ms)CI (400 ms)CI spike (2,300 ms)Verdict
Instant textContent()Fails at 0 msFails at 0 msFails at 0 msRaces every network call
waitForTimeout(2000)Wastes 1,920 msWastes 1,600 msFails at 2,000 msSlow and still flaky
Web-first toHaveText (5 s)Passes in ~80 msPasses in ~400 msPasses in ~2,300 msFast 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"):

"JAVASCRIPT"
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). Calling isVisible() first returns a plain boolean once and disables Playwright's auto-retry.
  • Waiting for networkidle as a universal sync hook. Background analytics, WebSockets, or polling keep networkidle pending 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, wrap queryByRole('progressbar') inside await waitFor(() => expect(...).not.toBeInTheDocument()) (or waitForElementToBeRemoved).
  • "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 for nth=1.
  • "If you stub PATCH /profile with page.route, how do you still catch real backend bugs?" Use page.route for 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 →

Original OfferVibe question. Playwright assertions · Playwright locators · Testing Library queries · Testing Library async utilities · ARIA status role (MDN).
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.