Forked from dwiyatci/faketimers-polling-workaround.js
Created
August 8, 2022 17:06
-
-
Save kjendrzyca/d2bd2d6082d87ee3d7309783afacf6a8 to your computer and use it in GitHub Desktop.
Jest Timers and Promises in polling.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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