-
Notifications
You must be signed in to change notification settings - Fork 31
/
index.ts
52 lines (47 loc) · 1.39 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { getSetTimeoutFn } from "./helpers";
const defaults = {
timeout: 4500,
interval: 50
};
/**
* Waits for the expectation to pass and returns a Promise
*
* @param expectation Function Expectation that has to complete without throwing
* @param timeout Number Maximum wait interval, 4500ms by default
* @param interval Number Wait-between-retries interval, 50ms by default
* @return Promise Promise to return a callback result
*/
const waitForExpect = function waitForExpect(
expectation: () => void | Promise<void>,
timeout = defaults.timeout,
interval = defaults.interval
) {
const setTimeout = getSetTimeoutFn();
// eslint-disable-next-line no-param-reassign
if (interval < 1) interval = 1;
const maxTries = Math.ceil(timeout / interval);
let tries = 0;
return new Promise((resolve, reject) => {
const rejectOrRerun = (error: Error) => {
if (tries > maxTries) {
reject(error);
return;
}
// eslint-disable-next-line no-use-before-define
setTimeout(runExpectation, interval);
};
function runExpectation() {
tries += 1;
try {
Promise.resolve(expectation())
.then(() => resolve())
.catch(rejectOrRerun);
} catch (error) {
rejectOrRerun(error);
}
}
setTimeout(runExpectation, 0);
});
};
waitForExpect.defaults = defaults;
export default waitForExpect;