Querying like a user
Testing Library encourages finding elements the way people do, by their role, label, or visible text, rather than by CSS classes or test ids. This makes tests accessible and resilient.
Query priority
- getByRole the top choice, matches the accessibility tree such as a button or heading.
- getByLabelText best for form fields tied to a label.
- getByText for non interactive content.
- getByTestId an escape hatch when nothing else fits.
Variants matter
- getBy throws if the element is missing, use for things that should exist now.
- queryBy returns null instead of throwing, use to assert absence.
- findBy returns a promise, use for elements that appear after async work.
Choosing role first nudges you toward markup that is also usable by assistive technology.
Key idea
Prefer role and label queries so tests mirror real users and reward accessible markup.