我正在try 使用Jest在NodeJS中为一个函数编写一个测试,该函数一个接一个地调用两个异步函数. 我想延迟Funca,期望函数B不被调用,然后运行计时器并期待函数B被调用.
代码如下所示
//module1.js
async function mainFunc() {
await module2.funcA()
await module2.funcB()
}
//module2.js
async function funcA(){
// making some async operation
}
async function funcB(){
// making some async operation
}
我试着这样嘲笑Funca的实现:
const spyOnFuncA = jest.spyOn(module2, 'funcA').mockImplementation(async () => new Promise((r) => setTimeout(r, 1000)))
然后在测试中执行如下操作:
test('Should not call second function until first function resolved', async () => {
jest.useFakeTimers()
const spyOnFuncA = jest.spyOn(module2, 'funcA').mockImplementation(async () => new Promise((r) => setTimeout(r, 1000)))
const spyOnFuncB = jest.spyOn(module2, 'funcB').mockImplementation()
mainFunc()
expect(spyOnFuncA).toBeCalled()
expect(spyOnFuncB).not.toBeCalled()
jest.runAllTimers()
expect(spyOnFuncB).toBeCalled()
})
我认为这里的问题是jest.useFakeTimers
与mock Implementation中的setTimeout相冲突
你知道我该怎么测试这个吗?
会很感激任何 idea
干杯!