Common Async Testing Antipatterns
You'll learn the most frequent mistakes developers make when testing async React components—pitfalls that create flaky, unreliable tests.
The Problem with Async Testing
When components fetch data or update asynchronously, tests become timing-dependent. Three common antipatterns create tests that sometimes pass, making your test suite unreliable—like a smoke detector that only works on Tuesdays.
Antipattern 1: Arbitrary setTimeout Delays
// ❌ BAD: Guessing how long to wait
test('shows data after loading', async () => {
render(<UserProfile id="123" />);
await new Promise(resolve => setTimeout(resolve, 1000));
expect(screen.getByText(/john doe/i)).toBeInTheDocument();
});
Why it's bad: You're guessing. Maybe 1000ms works on your machine, but fails on CI. You're testing your patience, not your component.
Antipattern 2: getBy Queries for Async Content
// ❌ BAD: getBy throws immediately if element doesn't exist
test('shows loaded user', async () => {
render(<UserProfile id="123" />);
const name = screen.getByText(/john doe/i); // Throws before data arrives!
expect(name).toBeInTheDocument();
});
Why it's bad: getBy doesn't wait—it explodes instantly if the element isn't already there.
Antipattern 3: Missing await Keywords
// ❌ BAD: Forgot to await findBy
test('shows loaded user', () => {
render(<UserProfile id="123" />);
screen.findByText(/john doe/i); // Returns a promise, never awaited!
// Test completes before data loads
});
Why it's bad: The test exits before async operations complete, creating false positives.
The Correct Approach
Use findBy queries or waitFor with proper await:
// ✅ GOOD: Wait for actual DOM changes
test('shows loaded user', async () => {
render(<UserProfile id="123" />);
expect(await screen.findByText(/john doe/i)).toBeInTheDocument();
});
Key Takeaway: Never use arbitrary timeouts, always use findBy or waitFor for async content, and never forget await on promises—let React Testing Library's built-in waiting mechanisms handle timing for you.