React 测试库如何使用 waitFor

lom*_*ine 7 javascript reactjs jestjs react-testing-library

我正在学习有关反应测试的教程。本教程有一个像这样的简单组件来显示测试异步操作:

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
Run Code Online (Sandbox Code Playgroud)

而测试文件是这样的:

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')
  });
Run Code Online (Sandbox Code Playgroud)

终端表示waitForElement已弃用and to usewaitFor`。

我如何waitFor在这个测试文件中使用?

Zso*_*ros 8

如果您正在等待外观,您可以像这样使用它:

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

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

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

  • 是否也可以使用“act”函数来包装断言?根据文档,我不明白在哪种情况下使用“act”,在哪种情况下使用“waitFor”。 (7认同)