我如何用玩笑测试承诺延迟? [英] How do I test promise delays with jest?
问题描述
这是我用来延迟进程的代码(用于退避)
Here's my code which I use to delay process (for backoff)
export function promiseDelay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
我想测试它,但我不能.我尝试使用 fakeTimers 但我的测试永远不会结束.
I would want to test it but I'm not able to. I tried working with fakeTimers but my test never ends.
test('promiseDelay delays for 1s', async (done) => {
jest.useFakeTimers();
Promise.resolve().then(() => jest.advanceTimersByTime(100));
await promiseDelay(100);
});
推荐答案
promiseDelay
返回一个在 ms
之后解析的 Promise
所以在 then
中调用一个 spy
code> 并测试 spy
是否在不同的时间间隔后被调用:
promiseDelay
returns a Promise
that resolves after ms
so call a spy
in then
and test to see if the spy
has been called after different intervals:
describe('promiseDelay', () => {
beforeEach(() => { jest.useFakeTimers(); });
afterEach(() => { jest.useRealTimers(); });
test('should not resolve until timeout has elapsed', async () => {
const spy = jest.fn();
promiseDelay(100).then(spy); // <= resolve after 100ms
jest.advanceTimersByTime(20); // <= advance less than 100ms
await Promise.resolve(); // let any pending callbacks in PromiseJobs run
expect(spy).not.toHaveBeenCalled(); // SUCCESS
jest.advanceTimersByTime(80); // <= advance the rest of the time
await Promise.resolve(); // let any pending callbacks in PromiseJobs run
expect(spy).toHaveBeenCalled(); // SUCCESS
});
});
注意测试代码是同步的,Timer Mocks make setTimeout代码> 同步但
then
在 PromiseJobs
中排队回调,因此在测试 spy
是否已被调用之前,需要允许任何排队的回调运行.
Note that test code is synchronous and Timer Mocks make setTimeout
synchronous but then
queues a callback in PromiseJobs
so any queued callbacks need to be allowed to run before testing if the spy
has been called.
这可以通过使用 async
测试函数并在已解析的 Promise
上调用 await
来完成,这有效地将测试的其余部分排在PromiseJobs
的结尾允许任何挂起的回调在测试继续之前运行.
This can be done by using an async
test function and calling await
on a resolved Promise
which effectively queues the rest of the test at the end of PromiseJobs
allowing any pending callbacks to run before the test continues.
在我的回答此处中提供了有关承诺和假计时器如何交互的其他信息.
Additional information about how promises and fake timers interact is available in my answer here.
这篇关于我如何用玩笑测试承诺延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!