Course contentsShow
← React
Lesson 2052 of 2,39646. Testing React with RTLFree lesson

The Query Priority: getByRole First

Why getByRole is the most resilient query and how it mirrors how users interact with your app.

The Query Priority: getByRole First

You'll learn why getByRole is RTL's recommended starting point for finding elements in your tests.

The Core Idea

When React Testing Library offers multiple query methods (getByText, getByLabelText, getByTestId, etc.), it's not a buffet where all choices are equal. getByRole is explicitly prioritized because it mirrors how assistive technologies like screen readers navigate your app — and thus how many real users experience it.

Every interactive element has an implicit or explicit ARIA role: buttons are button, links are link, text inputs are textbox, headings have heading with levels. When you query by role, you're verifying that:

  1. The element exists in the DOM
  2. It's semantically correct (a button is actually a <button>, not a styled <div>)
  3. It's accessible to all users, not just sighted mouse users

Why It's Most Resilient

Consider this: if you refactor a button's text from "Submit" to "Send", a getByText('Submit') test breaks. But getByRole('button', { name: /submit/i }) guides you toward proper accessibility — the accessible name matters more than implementation details.

Think of it like this: getByRole tests what the user can do and perceive, while other queries often test how you built it. A blind user doesn't care if you used a <span> or <div> — they care if the screen reader announces "button" when they focus it.

RTL's philosophy is simple: if your test can't find an element by role, neither can assistive technology — and that's a bug in your app, not your test.

Key Takeaway: Always start with getByRole when querying elements — it validates both functionality and accessibility simultaneously, making your tests resilient to implementation changes while catching real user experience issues.