【发布时间】:2019-12-23 08:09:53
【问题描述】:
我正在尝试测试一个可以进行调用并处理大量调度的排队组件。我想用一个模拟 api 来测试它,其中 api 响应会像在现实生活中一样被延迟,但我想使用模拟计时器并伪造时间的流逝。在下面的简单示例中,被测对象是 Caller 对象。
function mockCall(): Promise<string> {
return new Promise<string>(resolve => setTimeout(() => resolve("success"), 20));
}
const callReceiver = jest.fn((result: string) => { console.log(result)});
class Caller {
constructor(call: () => Promise<string>,
receiver: (result: string) => void) {
call().then(receiver);
}
}
it("advances mock timers correctly", () => {
jest.useFakeTimers();
new Caller(mockCall, callReceiver);
jest.advanceTimersByTime(50);
expect(callReceiver).toHaveBeenCalled();
});
我认为这个测试应该通过,但是 expect 在计时器提前之前被评估,所以测试失败。如何编写此测试以使其通过?
顺便说一句,如果我使用真正的计时器并将expect 延迟超过 20 毫秒,则此测试确实通过了,但我特别感兴趣的是使用假计时器并通过代码推进时间,而不是等待实时时间过去.
【问题讨论】:
标签: javascript typescript unit-testing timer jestjs