Skip to main content

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.

Async test loop
1Trigger one unit of user work
2React schedules / flushes related updates
3Await the observable condition
4Assert committed UI

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.

Should this test call act directly?
Using Testing Library render/user-event normallyUsually no; await the library helper and observable state
Using createRoot or low-level React test infrastructureYes, direct act may be appropriate
Manually advancing an external update source/timerPossibly; integrate advancement with the test framework and React flush

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);
});
Timing guess vs deterministic wait
Arbitrary delay
Hope enough time elapsed → slow + flaky
Observable wait
Wait until promised UI/condition exists

findBy, waitFor, and disappearance​

findBy
An element should appear asynchronously.
waitFor
A condition/side effect should eventually become true.
waitForElementToBeRemoved
Known content should disappear.
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();
Mutation UI contract
Intent
Save
Pending
Disabled / progress UI
Outcome
Success or useful error

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();
Test Suspense from the user's perspective
Child cannot finish
Compatible resource is pending
Fallback is visible
Assert meaningful loading UI
Boundary retries and reveals
Assert final content

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();
Urgent and transition work have different observable promises
Urgent
Input reflects typing immediately
Transition
Expensive result work may lag / restart
Committed result
Assert final content

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();
Deferred UI contract
Canonical input
react
Stale results
Previous committed result can remain visible
Deferred catch-up
New result eventually commits

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.

Complete optimistic test
1User mutation intent
2Optimistic projection appears
3Server/request settles
4Converge to canonical result OR rollback

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.

Render attempts are not user-visible history
Attempt A
May be discarded
Attempt B
May be interrupted
Commit
Assert states the product promises

Flaky async test checklist​

  1. Remove arbitrary sleeps.
  2. Identify the observable state that should be awaited.
  3. Await user interactions.
  4. Control network/Promise boundaries deterministically.
  5. Avoid exact render-count assertions.
  6. Integrate fake timers correctly with React updates.
  7. Prevent state leakage between tests.
  8. Keep each test focused on one behavior sequence.

Interview questions​

  1. What problem does act solve?
  2. Why should app tests usually prefer Testing Library helpers over direct act?
  3. What is the difference between findBy and waitFor?
  4. How should Suspense be tested without coupling to internal Promise mechanics?
  5. How do you test useDeferredValue from the user's perspective?
  6. Which states should an optimistic mutation test cover?
  7. Why are exact render-count assertions fragile in concurrent React?

References​