Course contentsShow
← React
Lesson 2150 of 2,39647. Testing Patterns and Best PracticesFree lesson

Testing useEffect with Async Operations

Render components that trigger effects, wait for side effects to complete with waitFor, then assert the resulting state.

Testing useEffect with Async Operations

You'll learn how to test components that perform asynchronous side effects inside useEffect by rendering them, waiting for effects to complete, and asserting the resulting state.

The Core Pattern

When a component triggers async operations in useEffect (like fetching data or setting timers), you need to:

  1. Render the component
  2. Wait for the effect to complete using waitFor
  3. Assert the final state after side effects have resolved

This is different from testing user-triggered async operations—here, the component initiates the effect automatically on mount or when dependencies change.

Why This Matters

useEffect runs after render, and async operations inside it complete even later. Without waiting, your test will check the DOM before the effect finishes, leading to false failures. Think of it like ordering food delivery: you can't check if the pizza arrived before giving it time to be delivered.

The Pattern in Practice

function UserProfile({ userId }: { userId: string }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then(res => res.json())
      .then(setUser);
  }, [userId]);

  return user ? <div>{user.name}</div> : <div>Loading...</div>;
}

// Test
test('loads and displays user on mount', async () => {
  render(<UserProfile userId="123" />);
  
  // Initially shows loading
  expect(screen.getByText('Loading...')).toBeInTheDocument();
  
  // Wait for effect to complete
  await waitFor(() => {
    expect(screen.getByText('John Doe')).toBeInTheDocument();
  });
});

The key is waitFor—it repeatedly checks your assertion until it passes or times out, giving the effect time to complete its async work.

Key Takeaway: Test components with async useEffect by rendering, using waitFor to wait for side effects to complete, then asserting the final DOM state—never assert immediately after render when async effects are involved.