Course contentsShow
← React
Lesson 2117 of 2,39647. Testing Patterns and Best PracticesFree lesson

Query by Role, Not Test IDs

Prefer getByRole and getByLabelText over data-testid to test how users actually interact with your components.

Query by Role, Not Test IDs

What you'll learn: How to write tests that mirror real user interactions by prioritizing semantic queries over arbitrary test IDs.

The Core Principle

When testing React components, you have many query options — getByRole, getByLabelText, getByText, or the escape hatch getByTestId. The best practice is clear: choose queries in order of how users actually perceive and interact with your UI.

Users don't see data-testid attributes. They see buttons, links, form fields with labels, and text content. Screen readers announce semantic roles. When you query by role or label, you're testing the accessible interface of your component — the same interface real users experience.

Why Role Queries Win

// ❌ Brittle, implementation-focused
const button = screen.getByTestId('submit-button');

// ✅ Tests what users experience
const button = screen.getByRole('button', { name: /submit/i });

The second approach forces accessibility. If getByRole can't find your button, maybe it's not properly accessible. Test IDs hide these problems — they work even when your UI is inaccessible.

The Priority in Practice

  1. getByRole — buttons, links, headings, form controls
  2. getByLabelText — form fields with associated labels
  3. getByText — non-interactive content users read
  4. getByTestId — only when semantic queries aren't possible

This isn't just about testing philosophy — it's about ensuring your components work for everyone, including users with assistive technologies.

Key Takeaway: Query components by their semantic roles and accessible names, not test IDs. If you can't query it semantically, your component likely has an accessibility problem worth fixing before the test passes.