UPDATE: Safe to say this is basically a duplicate of Jest: Timer and Promise don't work well. (setTimeout and async function)
I have a function that repeats itself after performing an asynchronous function. I want to verify that jest.advanceTimersOnTime(5000)
continues to yield expect(doAsyncStuff).toHaveBeenCalledTimes(X);
.
I observe that we can reach the call to repeat the function but it does not "go through" when asking jest to advance timers. It does work when you remove the async function preceding it. So it sounds like I have to get doAsyncStuff to "call through" or resolve some pending promise here?
Function
function repeatMe() {
setTimeout(() => {
doAsyncStuff.then((response) => {
if (response) {
console.log("I get here!");
repeatMe();
}
})
}, 5000);
}
Test
jest.useFakeTimers();
let doAsyncStuff = jest.spyOn(updater, 'doAsyncStuff');
doAsyncStuff.mockResolvedValue(true);
repeatMe();
jest.advanceTimersByTime(5000);
expect(doAsyncStuff).toHaveBeenCalledTimes(1);
jest.advanceTimersByTime(5000);
expect(doAsyncStuff).toHaveBeenCalledTimes(2); // Failed?