I have a function wait
async function wait(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
And I call this wait like this: await wait(5000);
from a different function.
I am writing unit test cases and it always executes wait and each test case waits for 5s.
How do I stub the setTimeout using Sinon?
I tried:
// Skip setTimeOut
clock = sinon.useFakeTimers({
now: Date.now(),
toFake: ['setTimeout']
});
await clock.tickAsync(4000);
await Promise.resolve();
But it didn't work.
Related post: setTimeout not triggered while using Sinon's fake timers
Github issue: https://github.com/sinonjs/fake-timers/issues/194#issuecomment-395224370
You can solve this in two ways.
The unit test should test the code logic, it's not integration tests. So, maybe you just need to make an assertion check the
wait
function is to be called with parameter. It's enough. We don't need to wait for 5000ms delay in the test case.sinon.useFakeTimers()
andclock.tick(5000)
.From the related post, we can do it like this:
index.ts
:index.test.ts
:unit test results: