waitFor() in React Testing Library

Testing React components often ends up meaning you wait for async behaviour.

There are lots of built in functions in React Testing Library, such as await screen.findByText(...).

Sometimes you will need to wait for things that aren't rendered.

Such as waiting until expect(window.fetch).toHaveBeenCalledTimes(1) to pass.

You can use await waitFor() for this!

import { waitFor } from '@testing-library/react';

test('waits for fetch to be called', async () => {
  render(<MyComponent />);

  await waitFor(() => {
    expect(
      window.fetch
    ).toHaveBeenCalledTimes(1);
  });
});

Loading full lesson content & code...

Ready to try running tests for this lesson?