getByText for Non-Interactive Content
You'll learn when and how to query elements by their visible text when they don't have semantic roles.
The Third Priority Query
You've learned that getByRole and getByLabelText are your top choices because they align with accessibility. But what about headings, paragraphs, error messages, or status text that don't have interactive roles or labels? That's where getByText comes in—it queries elements by their visible text content.
When to Use getByText
Think of getByText as your "readable content" query. Use it for:
- Headings and titles (when you're not testing ARIA hierarchy)
- Paragraphs and descriptions
- Error or success messages
- Static labels that aren't formally associated with inputs
- Non-interactive list items or cards
The key question: "Would a user find this element by reading its text?" If yes, getByText mirrors that behavior.
The Syntax
const element = screen.getByText('Welcome to the app');
// Or with a partial match
const element = screen.getByText(/welcome/i);
By default, it searches for exact matches. You can use regex patterns for case-insensitive or partial matching.
Why It's Lower Priority
getByText is less robust than role-based queries because text content changes more frequently than semantic structure. A designer might change "Submit" to "Send"—your test breaks. But a button's role as a button stays constant. Still, for non-interactive content where roles don't apply, getByText is the right tool.
Key Takeaway: Use getByText to query non-interactive content by visible text when role-based queries don't fit—it's the user-facing way to find headings, messages, and descriptive text.