← Lessons

quiz vs the machine

Silver1100

Frontend

Testing Library Queries

Pick the right query so tests mirror how users find elements.

4 min read · intro · beat Silver to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. Which query variant should you use for an element that appears after async work?

2. Why is getByRole the preferred query?