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

TextMatch: String, Regex, and Function

The three ways to match text: exact strings, regular expressions, and custom matcher functions.

TextMatch: String, Regex, and Function

You'll learn: How React Testing Library lets you match text in three flexible ways—exact strings, regular expressions, and custom functions—so you can find elements precisely without brittle tests.

The Core Idea

When you use queries like getByText or getByRole, you need to tell RTL what text to look for. RTL accepts three types of matchers:

  1. Exact string match: 'Submit' finds only "Submit"
  2. Regular expression: /submit/i finds "Submit", "submit", "SUBMIT"
  3. Custom function: (content, element) => content.includes('Sub') gives you full control

This flexibility lets you write tests that are resilient to minor text changes while still being specific enough to catch real bugs.

How It Works in Practice

Exact strings are strict by default—whitespace and case must match perfectly. Use when you know the exact text.

Regexes shine for case-insensitive matching (/submit/i) or partial matches (/loading/i finds "Loading..." or "Still loading"). They handle dynamic content gracefully.

Functions are your escape hatch. The function receives (content, element) and returns true for a match. Use them for complex logic like "contains two numbers" or "ends with a specific pattern." You already learned these in waitFor—the same concept applies to all text queries.

Analogy

Think of it like searching your email: exact match is typing the full subject line, regex is using wildcards, and the function is writing a custom filter rule.

When to Use Each

  • String: Known, stable text like button labels
  • Regex: Case-insensitive or partial matches
  • Function: Complex conditions (dates, counts, formatted text)

Key Takeaway: RTL's three text matchers—strings, regexes, and functions—give you the right precision level for every scenario, from exact labels to fuzzy content matching.