findBy for Async Elements
You'll learn how to wait for elements that appear after asynchronous operations using findBy queries.
The Core Problem
Sometimes elements don't exist in the DOM immediately after rendering. Maybe they appear after a data fetch, a timer, or a user action that triggers async logic. If you use getBy or queryBy, they'll look for the element right now and either throw or return null before the async operation completes.
This is where findBy queries shine.
How findBy Works
findBy queries return a Promise that resolves when the element appears in the DOM. RTL will keep checking for up to 1000ms (by default) before timing out.
Think of it like waiting at a bus stop: getBy checks once and yells if the bus isn't there. queryBy checks once and shrugs. findBy waits patiently, checking repeatedly until the bus arrives (or gives up after a timeout).
// ❌ This will fail if data loads async
const heading = screen.getByRole('heading', { name: /welcome/i });
// ✅ This waits for the element to appear
const heading = await screen.findByRole('heading', { name: /welcome/i });
Usage Pattern
Always use await with findBy queries, and make sure your test function is async:
test('displays user data after fetch', async () => {
render(<UserProfile userId="123" />);
// Wait for async data to load
const username = await screen.findByText(/john doe/i);
expect(username).toBeInTheDocument();
});
Key Takeaway: Use findBy queries with await when testing elements that appear after asynchronous operations — they automatically wait and retry until the element exists or times out.