React testing library how to use waitFor


I’m following a tutorial on React testing. The tutorial has a simple component like this, to show how to test asynchronous actions:

import React from 'react'

const TestAsync = () => {
  const [counter, setCounter] = React.useState(0)

  const delayCount = () => (
    setTimeout(() => {
      setCounter(counter + 1)
    }, 500)
  return (
      <h1 data-testid="counter">{ counter }</h1>
      <button data-testid="button-up" onClick={delayCount}> Up</button>
      <button data-testid="button-down" onClick={() => setCounter(counter - 1)}>Down</button>
export default TestAsync

And the test file is like this:

import React from 'react';
import { render, cleanup, fireEvent, waitForElement } from '@testing-library/react';
import TestAsync from './TestAsync'

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

  const counter = await waitForElement(() => getByText('1')) 


The terminal says waitForElement has been deprecated and to use waitFor instead.

How can I use waitFor in this test file?


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

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

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


Leave a Reply

Your email address will not be published. Required fields are marked *