Advanced
Testing with React Testing Library
Testing behaviour via the DOM, user-event, and async utilities.
React Testing Library (RTL) encourages testing components the way a user interacts with them — query by role/label/text, not by implementation details — so tests survive refactors.
RTL tests are a mystery shopper: they use the product like a customer and judge the outcome, not the wiring behind the counter.
Key concepts
1
Simulate interaction with @testing-library/user-event (realistic clicks/typing) and assert on visible output. Async UI uses findBy* queries and waitFor, which retry until the DOM settles.
`@testing-library/user-event`@testing-library/user-eventfindBy*waitFor
2
Mock the network (MSW) rather than the fetch function, so tests exercise real request/response handling. Custom hooks are tested with renderHook.
networkrenderHook
3
Pitfall: querying by data-testid everywhere or asserting on state/props — brittle and not user-facing. Interview angle: "why query by role over test-id?" — accessibility-aligned, resilient to markup changes, and closer to real usage.
Pitfall:Interview angle:data-testid
jsx
test('submits the form', async () => {
render(<Login onSubmit={onSubmit} />);
await userEvent.type(screen.getByLabelText(/email/i), 'a@b.com');
await userEvent.click(screen.getByRole('button', { name: /sign in/i }));
expect(onSubmit).toHaveBeenCalledWith({ email: 'a@b.com' });
});