In React Testing Library, both getBy and findBy are used to select elements in the DOM, but they behave differently in terms of timing and async handling.
1️⃣ getBy
- Synchronous query
- Throws an error immediately if the element is not found
- Use when the element already exists in the DOM
Example:
import { render, screen } from "@testing-library/react";
import Button from "./Button";
render(<Button text="Click me" />);
const button = screen.getByText("Click me"); // synchronous
expect(button).toBeInTheDocument();
Key Point:
- Good for static elements rendered immediately
2️⃣ findBy
- Asynchronous query
- Returns a Promise → waits for the element to appear (default timeout ~1000ms)
- Use when the element appears after some async action, like API calls or state updates
Example:
import { render, screen } from "@testing-library/react";
import AsyncButton from "./AsyncButton";
render(<AsyncButton />);
const button = await screen.findByText("Loaded"); // waits for element
expect(button).toBeInTheDocument();
Key Point:
- Ideal for elements that appear asynchronously
3️⃣ Quick Comparison
| Feature | getBy |
findBy |
|---|---|---|
| Nature | Synchronous | Asynchronous (returns Promise) |
| Wait for Element | No | Yes (waits up to timeout) |
| Throws Error | Immediately if not found | After timeout if not found |
| Use Case | Static elements | Async-loaded elements |
⚡ In short:
Use
getByfor elements that exist immediately, andfindByfor elements that appear after asynchronous actions like API responses or delayed renders.