Commit 2f038da5 authored by Lyza Danger Gardner's avatar Lyza Danger Gardner

Add component test utilities with `waitFor` function

- Add `waitFor` util for easier async testing 
parent 8fe3253e
/**
* Wait for a condition to evaluate to a truthy value.
*
* @param {() => any} condition - Function that returns a truthy value when some condition is met
* @param {number} timeout - Max delay in milliseconds to wait
* @param {string} what - Description of condition that is being waited for
* @return {Promise<any>} - Result of the `condition` function
*/
export async function waitFor(
condition,
timeout = 10,
what = condition.toString()
) {
const result = condition();
if (result) {
return result;
}
const start = Date.now();
return new Promise((resolve, reject) => {
const timer = setInterval(() => {
const result = condition();
if (result) {
clearTimeout(timer);
resolve(result);
}
if (Date.now() - start > timeout) {
clearTimeout(timer);
reject(new Error(`waitFor(${what}) failed after ${timeout} ms`));
}
});
});
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment