React 测试库 waitFor 不使用 setTimeout

React Testing Library waitFor not working with setTimeout

这是我的react组件(用于学习testing-library):

import '@babel/polyfill';
import React, {useState} from 'react'
import { render, cleanup, fireEvent, waitFor, getByTestId, getByText} from "@testing-library/react";
import '@testing-library/jest-dom'

const FirstTest = () =>{
  const [counter, setCounter] = useState(0)
  const delayFunc = ()=>{
    setTimeout(()=>{
      setCounter(counter+1)
    }, 5000)
  }
  return (
    <div>
      <h1 data-testid="h1counter">{counter}</h1>
      <button data-testid="buttonAdd" onClick={delayFunc}>+</button>
      <button
        disabled
        data-testid="buttonDown"
        onClick={()=> setCounter(counter-1)}
        >-</button>
    </div>
  )
}

这是我的测试代码:

afterEach(cleanup)
it('delay counter', async() =>{
  const { getByTestId } = render(<FirstTest />)
  fireEvent.click(getByTestId('buttonAdd'))
  await waitFor(()=> {
    expect((getByTestId("h1counter")).textContent).toBe("1")  
  })
})

我的问题是为什么 waitFor 似乎不起作用,因为收到的结果是:“0”?

发生这种情况是因为 waitFor 的默认超时为 1000 毫秒,而您的状态更改仅在点击事件后 5000 毫秒发生。

您可以减少 setTimeout 延迟 and/or 增加 waitFor 超时,但更好的解决方案是在测试期间 mock the timers using jest.useFakeTimers()