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:
- Roles (
getByRole) - semantic meaning - Labels (
getByLabelText) - form accessibility - Text (
getByText) - visible content - 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.