Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjendrzyca/d2bd2d6082d87ee3d7309783afacf6a8 to your computer and use it in GitHub Desktop.
Save kjendrzyca/d2bd2d6082d87ee3d7309783afacf6a8 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