Skip to content
fa
Search Frontend Atlas
Search questions and concepts across the handbook.
Accessibility, Security & Testingadvanced11 min read

How do you test async UI behavior and race conditions deterministically?

Control time and response ordering rather than relying on arbitrary sleeps.

Useful prerequisites

Async UI tests often pass on a developer’s machine and fail in CI because the test relies on timing it does not control. A request can finish before or after another request, and both orders are possible in a real application. A useful test makes that ordering explicit instead of hoping the scheduler behaves a certain way.

Async UI tests often pass on a developer’s machine and fail in CI because the test relies on timing it does not control. A request can finish before or after another request, and both orders are possible in a real application. A useful test makes that ordering explicit instead of hoping the scheduler behaves a certain way.

The quick version

Use deferred promises or controllable network handlers to force the ordering under test. Assert that stale results cannot overwrite newer state and that cancellation/error states are handled correctly.

Build the mental model

A sleep-based test assumes scheduler timing and is inherently fragile. Use fake timers only for timer behavior; use explicit promise resolution to test concurrency ordering.

See it in code

const first = deferred<Result>();
const second = deferred<Result>();
startSearch('a', first.promise);
startSearch('ab', second.promise);
second.resolve(resultFor('ab'));
first.resolve(resultFor('a'));
expect(screen.getByText('ab results')).toBeVisible();

Where it gets tricky

Use deferred promises or a network mock to resolve requests in in a controlled order that makes the race reproducible. Assert both the visible result and the absence of stale side effects. Also test unmount during an in-flight request, abort rejection, duplicate submit, and retry. Avoid sleeps: tests should control the event ordering they need to prove.

A common misunderstanding

Testing only the final happy path does not expose response reordering bugs.

What this changes in an application

Test cancellation, unmount during work, duplicate submit, timeout, retry, and error propagation. Unknown execution paths should fail loudly rather than disappear into logs.

Questions worth exploring next

  • How do you prove the stale request cannot win?
  • When are fake timers appropriate?

References and next steps

Explore next