Skip to content

Instantly share code, notes, and snippets.

@sorenlouv
Last active April 1, 2020 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sorenlouv/440ff8bfd0066755e5df40a83bf74444 to your computer and use it in GitHub Desktop.
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.
/*
* 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