Skip to content

Instantly share code, notes, and snippets.

@dwiyatci
Last active August 8, 2022 17:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dwiyatci/740a52a08eb6147baa1f0be9b4f38785 to your computer and use it in GitHub Desktop.
Save dwiyatci/740a52a08eb6147baa1f0be9b4f38785 to your computer and use it in GitHub Desktop.
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