Testing React Components
Test React components by user behavior: Testing Library queries, user-event, async, and what not to assert.
- react
- testing-react
Effective React tests assert what users see and do, not internal state or CSS class soup. Testing Library encodes that bias: query by role and label, fire real interactions, await outcomes.
Docs: React Testing Library, Jest / Vitest.
Minimal test
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Counter } from './Counter';
test('increments on click', async () => {
const user = userEvent.setup();
render(<Counter />);
await user.click(screen.getByRole('button', { name: /increment/i }));
expect(screen.getByText(/count: 1/i)).toBeInTheDocument();
});
Query priority
getByRolegetByLabelText/getByPlaceholderTextgetByTextgetByTestIdlast resort
Accessible names make tests and a11y improve together (accessibility patterns).
Async UI
expect(await screen.findByRole('heading', { name: /profile/i })).toBeVisible();
findBy* waits. Mock network with MSW for realism.
What not to test
- Private state variables.
- Snapshotting huge trees as the only assertion.
- Implementation details (
useStatecall counts). - Third-party library internals.
Hooks and boundaries
Test hooks via a small harness component or renderHook. Test error boundaries by rendering a throwing child and asserting fallback UI.
Interview out-loud
“I test components through the UI with Testing Library: roles, labels, user-event, and async findBy. I mock the network at the boundary, avoid testing implementation details, and treat accessibility-friendly queries as a feature, not a chore.”
Related on this site
Further reading
Edge cases worth rehearsing
Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.
Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.
When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.
Quick self-test
Explain the concept in 60 seconds, write a minimal code sample from memory, name one footgun, and point to the primary docs. If any of those fail, reread the worked example and rebuild it in a scratch file until the model sticks under interview pressure.
Edge cases worth rehearsing
Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.
Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.
When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.
Related guides
- useCopyToClipboard HookCopy text with navigator.clipboard, fallback execCommand, transient copied state, and permissions that fail in insecure contexts.
- useDebouncedValue HookDebounce a changing value in React without firing effects on every keystroke. Cleanup, leading vs trailing, and the stale timer that updates unmounted state.
- useEventListener HookAttach a window, document, or element listener with a stable handler ref so you do not rebind on every render. Capture option and target changes.
- useFetch With AbortControllerFetch in an effect with a signal, ignore aborted errors, and prevent the slow response from winning a race after the url changes.
- useIdle HookDetect idle users: reset a timer on input events, fire idle after timeout, and decide whether mount starts the timer immediately.