Simplifies testing promise-returning-functions that executes timers (setTimeout / setInterval). The helper `runTimersUntilResolved` will run the timers repeatedly until the promise resolves. Jest helper.
/* | |
* 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