【问题标题】:clearTimeout test not working with jest.useFakeTimers()clearTimeout 测试不适用于 jest.useFakeTimers()
【发布时间】:2021-08-18 13:23:29
【问题描述】:

我正在尝试迁移到 jest.useFakeTimers() 的“现代”版本,这不是版本 27.x 中的默认设置。
我的测试有一些问题,因为 Jest 一直说像 clearTimeoutsetInterval 这样的函数不是 jest mocks:

// Poster.ts
// This is the class method I'm testing

startInterval(interval = 1800000) {
  this._interval && clearTimeout(this._interval)

  this._interval = (setInterval(
    () =>
      this.post()
        .then((result) => {
          this.runHandlers('autopostSuccess', result)
          return result
        })
        .catch((error) => this.runHandlers('autopostFail', error)),
    interval
  ) as unknown) as number
  return this._interval
}
// Poster.test.ts
describe('startInterval method', () => {
  const p = new Poster({ client: {} })
  beforeEach(() => {
    jest.useFakeTimers()
  })
  afterEach(() => {
    jest.useRealTimers()
  })

  it('should call clearTimeout (but only from the second use)', () => {
    const firstID = p.startInterval()
    expect(clearTimeout).not.toHaveBeenCalled() // This line fails with the following error
    p.startInterval()
    expect(clearTimeout).toHaveBeenCalledTimes(1)
    expect(clearTimeout).toHaveBeenLastCalledWith(firstID)
  })

  // ...
})

错误:

expect(received).not.toHaveBeenCalled()

Matcher error: received value must be a mock or spy function

所以,它抱怨clearTimeout 不是一个模拟,即使我使用的是jest.useFakeTimers()

版本:

  • jest@27.0.3
  • ts-jest@27.0.2
  • typescript@4.2.4
  • 节点@12.14.0

我确定我在这里遗漏了一些东西,也许我以错误的方式使用useFakeTimers,但method docspage on Timer Mocks 都没有帮助我。

有人知道为什么我的测试不起作用吗?

【问题讨论】:

  • 我对 clearTimeout 模拟有同样的问题。有这方面的消息吗?
  • @eMko 不,不幸的是。我没有时间进一步调查:/

标签: node.js typescript unit-testing jestjs ts-jest


【解决方案1】:

经过一番挖掘,我找到了正确的方法。

答案在此issue 讨论中。

Jest 自动将间谍添加到假计时器中。我们不再这样做,人们需要这样做,例如jest.spyOn(global, 'setTimeout') 自己。

这对我有用。只需添加jest.spyOn(global, 'clearTimeout') 即可。也许你甚至不需要jest.useFakeTimers() 声明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-21
    • 2019-09-25
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 2022-11-24
    • 2020-09-20
    • 1970-01-01
    相关资源
    最近更新 更多