Test async effects and error states
Control asynchronous dependencies instead of sleeping
Async tests must distinguish the pending, success, empty and error states. The most reliable way to hold a component in pending state is to provide a promise that the test controls. Do not depend on network timing or arbitrary delays. The component below accepts a load function, starts a request inside an Effect, and ignores results after cleanup. Changing the retry attempt starts another load. The caller must pass a stable load function. In this example cleanup prevents obsolete updates but does not abort underlying work; a real request adapter should use an AbortSignal when possible.
import React, { useEffect, useState } from 'react';export default function Catalogue({ load }) { const [attempt, setAttempt] = useState(0); const [view, setView] = useState({ kind: 'loading' }); useEffect(() => { let active = true; setView({ kind: 'loading' }); Promise.resolve().then(() => load()).then(items => { if (active) setView({ kind: 'ready', items }); }, () => { if (active) setView({ kind: 'error' }); }); return () => { active = false; }; }, [load, attempt]); if (view.kind === 'loading') return <p role="status">Loading seeds</p>; if (view.kind === 'error') return <><p role="alert">Could not load seeds</p> <button type="button" onClick={() => {setView({kind:'loading'});setAttempt(n => n + 1);}}>Retry</button></>; if (view.items.length === 0) return <p role="status">No seeds available</p>; return <ul aria-label="Seed catalogue">{view.items.map(item => <li key={item.id}>{item.name}</li>)}</ul>;}The load adapter promises a validated array of records with unique IDs. An invalid response must reject before reaching this view. Pending is visible until resolution; rejected requests display an alert and Retry; a successful empty array produces an explicit empty message. An obsolete promise cannot overwrite the latest view after cleanup. StrictMode may call the load adapter more than once during development; any network adapter must tolerate this and support cancellation. Retry in this simple fixture is sequential, not a general concurrency strategy.
Resolve or reject the request explicitly
import React, { act } from 'react';import { afterEach, expect, test, vi } from 'vitest';import { cleanup, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import '@testing-library/jest-dom/vitest';import Catalogue from './Catalogue.jsx';afterEach(cleanup);function deferred() { let resolve, reject; const promise = new Promise((yes, no) => {resolve = yes; reject = no;}); return {promise, resolve, reject};}test('pending, failure, retry and success', async () => { const first = deferred(); const second = deferred(); const load = vi.fn().mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise); const user = userEvent.setup(); render(<Catalogue load={load} />); expect(screen.getByRole('status')).toHaveTextContent('Loading seeds'); await waitFor(() => expect(load).toHaveBeenCalledTimes(1)); await act(async () => {first.reject(new Error('offline'));}); expect(await screen.findByRole('alert')).toHaveTextContent('Could not load seeds'); await user.click(screen.getByRole('button', {name:'Retry'})); await waitFor(() => expect(load).toHaveBeenCalledTimes(2)); expect(screen.getByRole('status')).toHaveTextContent('Loading seeds'); await act(async () => {second.resolve([{id:1,name:'Basil'}]);}); expect(await screen.findByRole('list', {name:'Seed catalogue'})).toHaveTextContent('Basil'); expect(screen.queryByRole('alert')).not.toBeInTheDocument();});test('empty response is not an error', async () => { render(<Catalogue load={async () => []} />); expect(await screen.findByText('No seeds available')).toBeInTheDocument(); expect(screen.queryByRole('alert')).not.toBeInTheDocument();});waitFor retries when its callback throws; a returned false does not request another retry. Keep interactions outside it, since the callback may execute more than once. The request counts here describe a fixture mounted without a StrictMode wrapper. For StrictMode add a separate test using fresh promises per invocation and check that obsolete results cannot replace current results after rerender or unmount. An assertion about call counts alone does not prove that stale data was ignored. The test code uses explicit act for promise settlement; findBy waits for the observable result. These component tests are staged, not executed here.
Use fake time only for time-dependent behavior
import { afterEach, expect, test, vi } from 'vitest';afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });test('notification is not delivered early', () => { vi.useFakeTimers(); const notify = vi.fn(); setTimeout(notify, 300); vi.advanceTimersByTime(299); expect(notify).not.toHaveBeenCalled(); vi.advanceTimersByTime(1); expect(notify).toHaveBeenCalledTimes(1);});Timers advance under the test rather than waiting in real time. If pending callbacks must complete before teardown, run only the intended pending timers first and then restore real time; this fixture has no pending work at success. For user-event with fake timers use its advanceTimers option connected to the runner, not a delay-null workaround. For request-level integration, MSW can intercept requests without a real API: choose a reviewed major version, register success/error handlers, reset overrides after each test and close the interceptor after the suite. MSW 2 uses onUnhandledRequest: error; MSW 3 migration guidance renames this to onUnhandledFrame and moves HTTP handler exports to msw/http. Do not mix those interfaces. No MSW runtime is available here, so this is a design note, not a tested configuration. In all lanes deny real network egress independently; a mock is not a security sandbox. Practice: create a stale-result test that resolves the newer request first and the older one last, and assert that the newer result remains visible.