Async React Testing — act, Suspense, Actions, and Transitions
Modern React can schedule work across Promises, Suspense, Transitions, form Actions, optimistic updates, and Effects. Tests should wait for observable states, not guessed amounts of time.
What act does
act lets React process updates associated with a unit of test work before assertions run.
await act(async () => {
root.render(<App />);
});
Current React guidance prefers the async form:
await act(async () => {
// render or trigger updates
});
Application tests using Testing Library usually do not need to wrap every operation manually because its helpers integrate with act.
Do not solve async tests with arbitrary sleeps
Avoid:
await new Promise(resolve => setTimeout(resolve, 500));
expect(screen.getByText('Saved')).toBeVisible();
Prefer the state you actually expect:
expect(await screen.findByText('Saved')).toBeVisible();
or:
await waitFor(() => {
expect(saveRequest).toHaveBeenCalledTimes(1);
});
findBy, waitFor, and disappearance
expect(await screen.findByRole('heading', { name: 'Aisha' })).toBeVisible();
await waitFor(() => {
expect(onSuccess).toHaveBeenCalledWith(expectedUser);
});
const spinner = screen.getByRole('status', { name: 'Loading profile' });
await waitForElementToBeRemoved(spinner);
Protect meaningful async state sequences
For a save flow, both pending and completion can be part of the contract:
await user.click(screen.getByRole('button', { name: 'Save' }));
expect(screen.getByRole('button', { name: 'Saving…' })).toBeDisabled();
expect(await screen.findByText('Saved successfully')).toBeVisible();
Suspense: assert the boundary contract
render(
<Suspense fallback={<p role="status">Loading user…</p>}>
<UserDetails userPromise={userPromise} />
</Suspense>,
);
expect(screen.getByRole('status', { name: 'Loading user…' })).toBeVisible();
resolveUser({ id: '42', name: 'Aisha' });
expect(await screen.findByRole('heading', { name: 'Aisha' })).toBeVisible();
Do not make “a Promise was thrown” the main application-test contract.
Transitions: protect responsiveness and eventual UI
await user.type(screen.getByRole('searchbox'), 'react');
expect(screen.getByRole('searchbox')).toHaveValue('react');
expect(await screen.findByRole('heading', { name: 'Results for react' })).toBeVisible();
Avoid scheduler implementation assertions and exact render counts.
Pending navigation
await user.click(screen.getByRole('link', { name: 'Billing' }));
expect(screen.getByText('Loading Billing…')).toBeVisible();
expect(await screen.findByRole('heading', { name: 'Billing' })).toBeVisible();
If the product preserves the previous page instead of showing a global fallback, assert that product contract instead.
useDeferredValue: test stale UI, not Hook internals
expect(screen.getByText('Result for rea')).toBeVisible();
await user.type(screen.getByRole('searchbox'), 'ct');
expect(screen.getByRole('searchbox')).toHaveValue('react');
expect(screen.getByText('Result for rea')).toBeVisible();
expect(await screen.findByText('Result for react')).toBeVisible();
Form Actions, useActionState, and useFormStatus
Test through the rendered form workflow:
await user.type(screen.getByLabelText('Display name'), 'Aisha');
await user.click(screen.getByRole('button', { name: 'Save profile' }));
expect(screen.getByRole('button', { name: 'Saving…' })).toBeDisabled();
expect(await screen.findByText('Profile saved')).toBeVisible();
Error state:
await user.click(screen.getByRole('button', { name: 'Create account' }));
expect(await screen.findByRole('alert')).toHaveTextContent(
'Email is already registered',
);
Do not reach into Hook tuples just to assert private pending/result values.
Optimistic UI must test convergence and rollback
await user.type(screen.getByLabelText('Message'), 'Hello');
await user.click(screen.getByRole('button', { name: 'Send' }));
expect(screen.getByText('Hello')).toHaveTextContent('Sending');
Then resolve the canonical result and assert convergence.
A happy-path-only optimistic test is incomplete if failure recovery is part of the product contract.
Error Boundaries
render(
<ErrorBoundary fallback={<p role="alert">Something went wrong</p>}>
<BrokenWidget />
</ErrorBoundary>,
);
expect(screen.getByRole('alert')).toHaveTextContent('Something went wrong');
Suppress expected console noise narrowly if the environment reports the deliberately triggered error. Never globally hide unexpected errors.
Effects and cleanup
const unsubscribe = vi.fn();
subscribe.mockReturnValue(unsubscribe);
const { unmount } = render(<OnlineIndicator />);
expect(subscribe).toHaveBeenCalled();
unmount();
expect(unsubscribe).toHaveBeenCalled();
Under Strict Mode, focus on the invariant: every committed subscription has matching cleanup.
Timers and controlled Promises
Fake timers can be useful for debounce, polling, delayed tooltips, and timeout-driven retries. Timer advancement that causes React updates must cooperate with the test framework's async/act behavior.
When possible, a controlled Promise is stronger than guessing timing:
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
Do not over-assert intermediate renders
Concurrent rendering may restart or abandon work before it commits.
Flaky async test checklist
- Remove arbitrary sleeps.
- Identify the observable state that should be awaited.
- Await user interactions.
- Control network/Promise boundaries deterministically.
- Avoid exact render-count assertions.
- Integrate fake timers correctly with React updates.
- Prevent state leakage between tests.
- Keep each test focused on one behavior sequence.
Interview questions
- What problem does
actsolve? - Why should app tests usually prefer Testing Library helpers over direct
act? - What is the difference between
findByandwaitFor? - How should Suspense be tested without coupling to internal Promise mechanics?
- How do you test
useDeferredValuefrom the user's perspective? - Which states should an optimistic mutation test cover?
- Why are exact render-count assertions fragile in concurrent React?
References
- https://react.dev/reference/react/act
- https://testing-library.com/docs/dom-testing-library/api-async/
- https://testing-library.com/docs/react-testing-library/intro/
- https://react.dev/reference/react/Suspense
- https://react.dev/reference/react/useTransition
- https://react.dev/reference/react/useDeferredValue
- https://react.dev/reference/react/useActionState
- https://react.dev/reference/react/useOptimistic