All topics
Testingbeginner

Queries and Roles in Testing Library

Learn the priority order of Testing Library queries and why role-based queries are the recommended default.

Testing Library provides several families of queries — getBy*, queryBy*, findBy* — each combined with a selector strategy like Role, LabelText, Text, PlaceholderText, or TestId. The official documentation publishes a deliberate priority order recommending which selector strategy to reach for first, with getByRole at the very top, since it most closely matches how assistive technology and visual users alike perceive an element's purpose.

Query priority is like choosing how to identify someone in a crowd: recognizing them by their actual role and name tag (getByRole) works the same way real people would find them, while relying on a hidden numbered sticker only testers can see (getByTestId) tells you nothing about whether an ordinary visitor could actually locate that person.

Key Concepts

1
getByRole('button', { name: 'Submit' }) finds an element by its accessibility role (as computed from its tag and ARIA attributes) and its accessible name (typically its visible text or aria-label), which has the useful side effect of implicitly testing accessibility — if your query can't find a button by role, it may indicate the actual markup doesn't expose the right role/accessible name to real assistive technology users either.
getByRole('button', { name: 'Submit' })aria-label
2
Lower-priority selectors like getByTestId should be treated as an escape hatch for elements that genuinely have no reasonable accessible role or text (like a purely decorative container), not a convenient default reached for because it's easy to add a data-testid attribute — over-relying on test IDs both signals and can encourage inaccessible markup, since the tests no longer pressure you to expose real accessible names.
getByTestIddata-testid
3
Interviewers frequently show a snippet using getByTestId for a button and ask candidates to rewrite it using a higher-priority query, expecting them to justify getByRole as both more resilient to refactors (a test ID is often an implementation detail unrelated to markup structure) and more meaningfully validating accessibility.
getByTestIdgetByRole