Testing Library's Idea

Query the way a person would. React Testing Library deliberately makes it awkward to reach into a component's internals and easy to find things by their accessible role, label or visible text.

That is a design position, not an inconvenience. A test that asserts a state variable equals 3 breaks on every refactor and proves nothing a user cares about. A test that clicks the button labeled Add and asserts the page now shows 3 survives any rewrite that keeps the behavior.

The query priority. Prefer getByRole, then getByLabelText, then getByText. Reach for a test id last and rarely.

There is a real benefit hidden in that order: a component you cannot query by role or label is usually a component with an accessibility problem. The test is telling you something true about the interface, not being difficult.

Assert what changed for the person. Not that a handler was called, not that state updated. That the number on screen changed, the error message appeared, the button became disabled.

You already built this instinct: the React course grades components by rendering them and driving them, for exactly this reason.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Async, and What Not to Test →
← Back