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

waitFor for Complex Async Assertions

Using waitFor to repeatedly check conditions until they pass or timeout.

waitFor for Complex Async Assertions

What you'll learn: How to use waitFor to repeatedly check conditions until they pass or timeout, handling complex async scenarios beyond simple element appearance.

The Problem with Simple Async Queries

You've learned findBy queries for waiting until elements appear, but sometimes you need more control. What if you need to wait for:

  • An element's text to change to a specific value?
  • Multiple conditions to be true simultaneously?
  • An element to disappear and then reappear?
  • A custom assertion that can't be expressed as a single query?

Enter waitFor

waitFor is RTL's Swiss Army knife for async assertions. It repeatedly executes a callback until it succeeds (no error thrown) or times out (default 1000ms).

Think of it like this: You're checking your mailbox for a specific letter. findBy says "wait until there's any mail." waitFor says "keep checking until the mail contains exactly what I'm looking for."

import { render, screen, waitFor } from '@testing-library/react';

// Wait for text content to update
await waitFor(() => {
  expect(screen.getByRole('status')).toHaveTextContent('Loaded');
});

// Wait for multiple conditions
await waitFor(() => {
  expect(screen.getByRole('button')).toBeEnabled();
  expect(screen.getByText(/success/i)).toBeInTheDocument();
});

// Custom condition
await waitFor(() => {
  const items = screen.getAllByRole('listitem');
  expect(items).toHaveLength(5);
});

When to Use It

Use waitFor when findBy isn't enough: checking changing content, multiple assertions, or complex DOM states that evolve over time.

Key Takeaway: waitFor lets you poll for complex conditions that go beyond just waiting for an element to appear—it's your tool for "keep checking until this assertion passes."