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

getByRole: Common Roles and Accessibility

Using button, textbox, heading, link, and other ARIA roles to find elements accessibly.

getByRole: Common Roles and Accessibility

You'll learn which ARIA roles help you find elements the way screen readers and assistive technologies do, making your tests both robust and accessible.

The Core Idea

getByRole is your primary query method in React Testing Library because it mirrors how users with assistive technologies interact with your app. Instead of hunting for elements by class names or test IDs, you query by their semantic role—what they actually are and do.

Think of roles as job titles in your UI. A <button> has the role of "button," an <input type="text"> has the role of "textbox," and a <h1> has the role of "heading." When you test by role, you're verifying that your markup is semantically correct—a huge accessibility win.

Common Roles You'll Use Daily

Here are the roles you'll reach for most often:

  • button – Any <button> or element with role="button"
  • textbox – Text inputs (<input type="text">, <textarea>)
  • heading – <h1> through <h6> (specify level with { level: 1 })
  • link – <a> elements with an href
  • checkbox – <input type="checkbox">
  • radio – <input type="radio">
  • combobox – <select> elements or custom dropdowns
  • img – Images with alt text

Why This Matters for Accessibility

If getByRole('button') can't find your clickable element, that's a red flag: screen readers might not recognize it as a button either. Your test becomes an accessibility audit. If you've used a <div onClick> without proper ARIA attributes, the test fails—pushing you toward better markup.

screen.getByRole('button', { name: /submit/i }) // ✅ Finds button with accessible name
screen.getByRole('heading', { level: 1 })       // ✅ Finds <h1>
screen.getByRole('textbox', { name: /email/i }) // ✅ Finds labeled input

Key Takeaway: Using getByRole with common roles ensures your components are both testable and accessible—if the test passes, assistive technologies can navigate your UI correctly.