【问题标题】:React testing library how to use waitForReact 测试库如何使用 waitFor
【发布时间】:2021-04-19 20:42:02
【问题描述】:

我正在关注 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

【问题讨论】:

    标签: javascript reactjs jestjs react-testing-library


    【解决方案1】:

    如果你是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()

    【讨论】:

    • 是否也可以使用act 函数包装断言?根据文档,我不明白在哪种情况下使用act,在哪种情况下使用waitFor
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2020-07-19
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2022-11-30
    相关资源
    最近更新 更多