Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Jest Timers and Promises in polling.
jest.useFakeTimers();
const pollingPromise = poll();
const cancelAdvance = advanceTimersContinuously();
const status = await pollingPromise;
cancelAdvance();
expect(status).toEqual('COMPLETE');
function advanceTimersContinuously() {
let isCancelled = false;
async function advance() {
let mockSetTimeoutFnCallCount = 0;
while (!isCancelled) {
// 1. Make sure the setTimeout mock being queued to be called.
await Promise.resolve();
const isMockSetTimeoutFnBeingCalled =
mockSetTimeoutFnCallCount !== setTimeout.mock.calls.length;
if (isMockSetTimeoutFnBeingCalled) {
mockSetTimeoutFnCallCount = setTimeout.mock.calls.length;
// 2. Fast forward and exhaust only currently pending timers.
jest.runOnlyPendingTimers();
// 3. Flush the "PromiseJobs".
await Promise.resolve();
}
}
}
advance();
return () => {
isCancelled = true;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.