React测试库如何使用waitFor

React testing library how to use waitFor

我正在关注 a tutorial 的 React 测试。本教程有一个像这样的简单组件,用于展示如何测试异步操作:

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

而测试文件是这样的:


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

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

  fireEvent.click(getByTestId('button-up'))

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

  expect(counter).toHaveTextContent('1')
});

终端显示 waitForElement 已被弃用,改为使用 waitFor

如何在此测试文件中使用 waitFor

如果你是 waiting for appearance,你可以这样使用它:

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

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

当您使用 getByText('1') 来获取该元素时,检查 .toHaveTextContent('1') 有点“奇怪”,所以我将其替换为 .toBeInTheDocument()