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

The Guiding Principle: Accessibility First

Queries prioritize accessible selectors (roles, labels) to encourage building accessible UIs.

The Guiding Principle: Accessibility First

You'll learn: Why React Testing Library encourages you to select elements the same way assistive technologies do.

The Core Philosophy

React Testing Library (RTL) follows a simple but powerful rule: if your test can't find an element the way a screen reader would, neither can your users.

RTL's query methods are deliberately designed to prioritize accessible selectors. When you use getByRole('button') instead of getByTestId('submit-btn'), you're not just writing a test—you're validating that your component is accessible. If the query fails, it's often because your markup is missing proper semantic HTML or ARIA attributes.

Why This Matters

Think of RTL as a "screen reader simulator" for your tests. When you write:

const button = screen.getByRole('button', { name: /submit/i });

You're testing exactly what a screen reader announces: "button, submit." If this query breaks, your actual users with disabilities will struggle too.

The hierarchy RTL recommends:

  1. Roles (getByRole) - semantic meaning
  2. Labels (getByLabelText) - form accessibility
  3. Text (getByText) - visible content
  4. Test IDs (getByTestId) - last resort only

This isn't just best practice—it's forcing you to build better UIs. A test that needs data-testid is often a red flag that your component lacks proper semantic structure.

Key Takeaway: RTL's query priority system isn't a testing preference—it's an accessibility audit built into every test you write. Write tests that pass for screen readers, not just for browsers.