Testing React components · core
React Testing Library: principles and query priority
React Testing Library renders components into a DOM and makes you find elements the way users and assistive technology do, so you query by role and accessible name first, then label and text, and use test ids only as a last resort.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Principle: test what the user sees and does, not component internals (state, props, instance methods). Refactors that keep behaviour should not break tests.
- Query priority: getByRole (with { name }), getByLabelText, getByPlaceholderText, getByText, getByDisplayValue; then getByAltText, getByTitle; last getByTestId.
- Variants: getBy throws if 0 or more than 1 match; queryBy returns null (use only to assert absence); findBy returns a promise and retries (default 1000 ms); *AllBy return arrays.
- Use screen.getBy... instead of destructuring from render; use within(element) to search inside a region; use jest-dom matchers (toBeInTheDocument, toBeDisabled, toHaveAccessibleName) for clear messages.
- If getByRole can't find your element, the component is probably not accessible (a div with onClick has no button role). The test is telling you about a real bug.
- Enzyme is dead (no React 18/19 adapter) and react-test-renderer is deprecated in React 19; RTL is the standard.
The red pen
Common traps: mistake → fix
Mistake: "Use data-testid everywhere, it's stable"
Fix: users can't see test ids; role/label queries also check accessibility.
Mistake: "Use queryBy to check something exists"
Fix: use getBy/findBy for presence and queryBy only for absence.
Mistake: "container.querySelector('.btn-primary') is fine"
Fix: it couples tests to CSS and markup details.
Easy to hard
Questions interviewers ask, easy to hard
- Why getByRole over getByTestId?
- getBy vs queryBy vs findBy: when do you use each?
- What does 'test behaviour, not implementation' look like in RTL?
- How would you test a modal with a form inside it?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.