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

Query Options: exact, normalizer, hidden

Customizing query behavior with exact matching, whitespace normalization, and hidden elements.

Query Options: exact, normalizer, hidden

You'll learn how to fine-tune React Testing Library queries for edge cases like partial text, whitespace variations, and hidden elements.

The Core Idea

React Testing Library queries accept an options object as their final argument, giving you surgical control over matching behavior. The three most useful options are:

  • exact: Controls whether text must match exactly or can be partial
  • normalizer: Defines how whitespace/casing is normalized before matching
  • hidden: Whether to include elements hidden from screen readers

Think of these as filters on a search tool—by default, RTL searches strictly, but sometimes you need to loosen the criteria.

How They Work

exact: false allows substring matching:

// Finds button with "Submit Form Now"
screen.getByText('Submit', { exact: false });

normalizer customizes whitespace handling. By default, RTL collapses multiple spaces and trims. You can override this:

// Preserve exact spacing
getByText('Hello  World', { 
  normalizer: (str) => str // no normalization
});

hidden: true includes elements with aria-hidden or CSS visibility rules:

// Finds elements even if hidden from assistive tech
getByText('Loading...', { hidden: true });

When to Use These

Use exact: false sparingly—usually for long dynamic text. Use custom normalizer when testing whitespace-sensitive content (like code blocks). Use hidden: true only when asserting something should be hidden, not as a workaround for poor queries.

Key Takeaway: Query options give you precision control, but reaching for them often signals you should reconsider your query strategy—most user interactions don't care about exact spacing or hidden elements.