Last active
August 8, 2022 17:06
-
-
Save dwiyatci/740a52a08eb6147baa1f0be9b4f38785 to your computer and use it in GitHub Desktop.
Jest Timers and Promises in polling.
This file contains hidden or 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