Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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>) {
let isResolved = false;
const p = fn();
p.finally(() => (isResolved = true));
while (isResolved === false) {
// tick
await new Promise((resolve) => setImmediate(resolve));
// run timers
return p;
// Example:
const res = await runTimersUntilResolved(() => myAsyncOperation())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment