【发布时间】:2021-08-18 13:23:29
【问题描述】:
我正在尝试迁移到 jest.useFakeTimers() 的“现代”版本,这不是版本 27.x 中的默认设置。
我的测试有一些问题,因为 Jest 一直说像 clearTimeout 和 setInterval 这样的函数不是 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 docs 和page on Timer Mocks 都没有帮助我。
有人知道为什么我的测试不起作用吗?
【问题讨论】:
-
我对 clearTimeout 模拟有同样的问题。有这方面的消息吗?
-
@eMko 不,不幸的是。我没有时间进一步调查:/
标签: node.js typescript unit-testing jestjs ts-jest