Last active
March 1, 2022 14:09
-
-
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
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
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