jest.runAllTimers() 抛出 TypeError

我正在尝试使用中的内置react-scripts test脚本运行以下测试create-react-app:


Timer.test.js


render(<Timer />)

const pauseButton = screen.getByText('pause')

const timerOutput = screen.getAllByRole('heading')[1]


describe('Timer', () => {

  test('renders Timer component', () => {

    expect(screen.getByText(/session/i)).toBeInTheDocument()

    expect(screen.getByText(/25/)).toBeInTheDocument()

  })


  test('counts down when unpaused', async () => {

    jest.useFakeTimers()

    fireEvent.click(pauseButton)

    setTimeout(

      fireEvent.click(pauseButton),

      1125

    )

    jest.runAllTimers()

    expect(timerOutput).toHaveTextContent('24:59')

  })

})

Jest 似乎工作正常,直到它到达jest.runAllTimers(),当我收到以下错误时:


 TypeError: callback.apply is not a function


      23 |       1125

      24 |     )

    > 25 |     jest.runAllTimers()

         |          ^

      26 |     expect(timerOutput).toHaveTextContent('24:59')

      27 |   })

      28 | 


      at node_modules/@jest/fake-timers/build/jestFakeTimers.js:524:25

      at callback (node_modules/@jest/fake-timers/build/jestFakeTimers.js:516:29)

      at FakeTimers._runTimerHandle (node_modules/@jest/fake-timers/build/jestFakeTimers.js:560:9)

      at FakeTimers.runAllTimers (node_modules/@jest/fake-timers/build/jestFakeTimers.js:193:12)

      at Object.<anonymous> (src/features/Timer.test.js:25:10)

我不知道发生了什么事。为什么它不能完成运行测试?


慕莱坞森
浏览 124回答 1
1回答

慕田峪7331174

你得到的错误可能是因为setTimeout使用。setTimeout接受一个函数作为第一个参数,但无论fireEvent.click(pauseButton). 将代码更改为:test('counts down when unpaused', async () => {&nbsp; &nbsp; jest.useFakeTimers();&nbsp; &nbsp; fireEvent.click(pauseButton)&nbsp; &nbsp; setTimeout(() =>&nbsp; fireEvent.click(pauseButton), 1125);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // ^ NOTE HERE&nbsp; &nbsp; jest.runAllTimers();&nbsp; &nbsp; expect(timerOutput).toHaveTextContent('24:59');&nbsp; })
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript