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
- Accessibility Patterns in ReactPractical React a11y: labels, focus management, keyboard, live regions, and composition patterns that stay accessible.
- Avoid Prop Drilling with CompositionStop threading props through intermediates: children slots, inversion of control, and when context is the right escape hatch.
- Batching State UpdatesHow React 18+ batches setState in events, timeouts, and promises: when updates flush and why double setState still works.
- Children Prop PatternsUsing children and slot props for flexible APIs: wrappers, compound components, and when to prefer explicit props.
- Client Component BoundariesWhere to put use client: push interactivity to leaves, serializable props, and children as server slots.