React testing library how to use waitFor

If you’re waiting for appearance, you can use it like this:

it('increments counter after 0.5s', async() => {
  const { getByTestId, getByText } = render(<TestAsync />);

  fireEvent.click(getByTestId('button-up'));
  
  await waitFor(() => {
    expect(getByText('1')).toBeInTheDocument();
  });
});

Checking .toHaveTextContent('1') is a bit “weird” when you use getByText('1') to grab that element, so I replaced it with .toBeInTheDocument().

Leave a Comment