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

getByRole with Accessible Name

Filtering by accessible name using the name option to find specific buttons or inputs.

getByRole with Accessible Name

You'll learn: How to precisely target elements by combining their role with their accessible name, avoiding ambiguity when multiple elements share the same role.

The Problem: Multiple Buttons, One Role

You've learned getByRole queries elements by their semantic role — button, heading, textbox, etc. But what happens when your component has three buttons? getByRole('button') would throw an error because multiple matches exist.

The solution: add a name filter to identify which specific button you want.

The Accessible Name

Every interactive element has an "accessible name" — the text screen readers announce. For buttons, this is typically:

  • The button's text content: <button>Submit</button>
  • An aria-label: <button aria-label="Close dialog">×</button>
  • An aria-labelledby reference

RTL's getByRole accepts a name option to filter by this accessible name:

// Component with multiple buttons
<div>
  <button>Cancel</button>
  <button>Submit</button>
  <button aria-label="Delete">🗑️</button>
</div>

// In your test
const submitButton = screen.getByRole('button', { name: 'Submit' });
const deleteButton = screen.getByRole('button', { name: 'Delete' });

Why This Matters

This technique mirrors how assistive technology users navigate — they identify elements by role and name. It's also more resilient than querying by test IDs or class names because it depends on user-facing content.

Think of it like finding a specific contact in your phone: searching just "John" isn't enough, but "John Smith" narrows it down perfectly.

Key Takeaway: Use getByRole with the name option to target specific elements when multiple share the same role — it's precise, accessible-first, and resilient to implementation changes.