-
Notifications
You must be signed in to change notification settings - Fork 1
/
wait.js
86 lines (75 loc) · 2.05 KB
/
wait.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// @flow
import React from 'react';
import enzymeToJson from 'enzyme-to-json';
import prettyFormat from 'pretty-format';
const { ReactElement, ReactTestComponent } = prettyFormat.plugins;
export type ValidatorFn = (wrapper: any) => boolean;
export type Config = {
interval: number,
timeout: number,
timeoutMessage: string,
logStructureOnTimeout?: boolean,
logStructureOnSuccess?: boolean
};
export const DEFAULT_CONFIG: Config = {
interval: 50,
timeout: 2000,
timeoutMessage: 'Timed out.',
logStructureOnTimeout: true,
logStructureOnSuccess: false
};
function printWrapper(
wrapper: any,
type: 'warn' | 'log',
message: string
): void {
if (console[type]) {
const wrapperAsJson = enzymeToJson(wrapper, { noKey: true });
console[type](
message,
prettyFormat(wrapperAsJson, {
plugins: [ReactTestComponent, ReactElement],
printFunctionName: true
})
);
console[type]('As JSON:\n', wrapperAsJson);
}
}
export function wait(
wrapper: any,
validatorFn: ValidatorFn,
config?: Config = DEFAULT_CONFIG
): Promise<void> {
const interval = config.interval || DEFAULT_CONFIG.interval;
const timeout = config.timeout || DEFAULT_CONFIG.timeout;
return new Promise((resolve, reject) => {
let retries = timeout / interval;
let intervalInstance;
intervalInstance = setInterval(() => {
if (validatorFn(wrapper) === true) {
clearInterval(intervalInstance);
if (config.logStructureOnSuccess) {
printWrapper(
wrapper,
'log',
'The render tree at the time of success:\n'
);
}
resolve();
} else {
retries -= 1;
if (retries < 0) {
clearInterval(intervalInstance);
if (config.logStructureOnTimeout) {
printWrapper(
wrapper,
'warn',
'The render tree at the time of timeout:\n'
);
}
reject(config.timeoutMessage || DEFAULT_CONFIG.timeoutMessage);
}
}
}, interval);
});
}