【发布时间】:2020-10-01 03:25:09
【问题描述】:
我正在使用Jest框架进行测试,我知道我必须调用done()函数,每当异步测试完成时,像这样
it("should be executed", (done)=>{
const callback = jest.fun(()=>{
expect(callback).toHaveBeenCalled();
done();
})
someFakeStream$.subscribe(callback);
})
现在我有以下场景,我想确保我的回调只触发一次,即使事件触发多次,所以我有
it("should be executed", (done)=>{
//I Want to ensure that this function invoces only once
const callback = jest.fun(()=>{
expect(callback).toHaveBeenCalled();
done();
})
someFakeStream$.subscribe(callback);
someFakeStream$.next();
someFakeStream$.next();
})
现在如果我让回调代码保持原样它不会起作用,因为完成函数将在第一次发射后被调用,我可以在这个方法上添加失败条件
const callback = jest.fun(()=>{
expect(callback).toHaveBeenCalled();
if (callback.mock.calls.length > 1) { // This will call fail if it's invoked twice
done.fail();
}
})
但现在我没有调用done() 方法,所以我会遇到开玩笑超时异常。
我该如何解决这个问题?
【问题讨论】: