Last active
April 1, 2020 08:10
-
-
Save sorenlouv/440ff8bfd0066755e5df40a83bf74444 to your computer and use it in GitHub Desktop.
Simplifies testing promise-returning-functions that executes timers (setTimeout / setInterval). The helper `runTimersUntilResolved` will run the timers repeatedly until the promise resolves. Jest helper.
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
/* | |
* Run timers (setInterval/setTimeout) every tick continuously until the promise has been resolved | |
*/ | |
async function runTimersUntilResolved(fn: () => Promise<any>) { | |
jest.useFakeTimers(); | |
let isResolved = false; | |
const p = fn(); | |
p.finally(() => (isResolved = true)); | |
while (isResolved === false) { | |
// tick | |
await new Promise((resolve) => setImmediate(resolve)); | |
// run timers | |
jest.runAllTimers(); | |
} | |
return p; | |
} | |
// Example: | |
const res = await runTimersUntilResolved(() => myAsyncOperation()) | |
expect(rest).toEqual('something'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment