findBy Queries: Built-in Async Waiting
What you'll learn: How findBy queries combine element selection with automatic async waiting, simplifying your test code.
The Convenience Layer Over waitFor
You've been using waitFor to handle async updates, but React Testing Library provides an even cleaner approach: findBy queries. These queries automatically retry until the element appears (or timeout occurs), eliminating the need to manually wrap your assertions in waitFor.
Think of findBy as a vending machine with patience: instead of repeatedly pressing the button yourself (waitFor + getBy), you press once and the machine automatically keeps trying until your snack drops.
The Simple Swap
When you write:
await waitFor(() => {
expect(screen.getByRole('alert')).toBeInTheDocument();
});
You can simplify to:
const alert = await screen.findByRole('alert');
expect(alert).toBeInTheDocument();
The findBy query handles the waiting and retrying internally. It's just waitFor + getBy wrapped in one convenient method.
All the findBy Variants
Every getBy query has a findBy equivalent:
findByRole('button', { name: /submit/i })findByText(/loading complete/i)findByLabelText('Email')findByPlaceholderText('Search...')
They all return promises that resolve when the element appears.
When to Use findBy
Use findBy when you're waiting for a single element to appear after an async operation. If you need more complex conditions (multiple elements, assertions about non-existence changing to existence), stick with waitFor. But for straightforward "wait for this to show up" scenarios, findBy is cleaner and more readable.
Key Takeaway: findBy queries combine element selection with automatic async waiting—they're your go-to for waiting on single elements to appear, replacing the waitFor + getBy pattern with cleaner, more expressive code.