Skip to content

Instantly share code, notes, and snippets.

@tlux
Last active March 1, 2022 14:09
Show Gist options
  • Save tlux/a0435cf09d5949ce19ffe08a14d9a5ea to your computer and use it in GitHub Desktop.
Save tlux/a0435cf09d5949ce19ffe08a14d9a5ea to your computer and use it in GitHub Desktop.
A simple function that resolves when a call eventually does not fail or rejects after a timeout - nice for tests performing async work
export default function eventually(callback, timeout = 2000, pollInterval = 50) {
return new Promise((resolve, reject) => {
let intervalTimer;
let lastError;
const timeoutTimer = setTimeout(() => {
if (!intervalTimer) return;
clearTimeout(intervalTimer);
reject(lastError || new Error('eventually timed out'));
}, timeout);
async function check() {
try {
const result = await callback();
clearTimeout(timeoutTimer);
resolve(result);
} catch (e) {
lastError = e;
intervalTimer = setTimeout(check, pollInterval);
}
}
check();
});
}
// You can use this in your tests to actively wait for changes:
//
// it('succeeds eventually', async () => {
// component.doSomething();
//
// await eventually(() => {
// expect(component.hasSomeDesiredState()).toBe(true);
// });
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment