-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
135 lines (113 loc) · 3.13 KB
/
index.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
function waitFor(fn, timeout, message) {
var elapsed = 0, recurStarted;
return new Promise(function(resolve, reject) {
function endWithRejection() {
reject(message || 'timeout');
}
function continuation(result) {
if (result) {
return resolve(result);
}
if (elapsed > timeout) {
return endWithRejection();
}
setTimeout(function () {
elapsed += new Date() - recurStarted;
recur();
}, 10);
}
function recur() {
recurStarted = new Date();
const value = fn();
if (isPromise(value)) {
Promise.race([
value.then(function(result) {
continuation(result);
}).catch(function() {
continuation(false);
}),
waitPromise(timeout - elapsed).then(function() {
return '###timeout###';
})
]).then(function(result) {
if (result === '###timeout###')
return endWithRejection();
});
} else {
continuation(value);
}
}
recur();
});
}
waitFor.hold = function(fn, timeout, message) {
return waitFor(function() {
const value = fn();
if (isPromise(value)) {
return value.then(function(result) {
return !result;
});
} else {
return !value;
}
}, timeout, message)
.then(function() {
throw 'did not hold';
})
.catch(function(err) {
if (err === 'did not hold')
throw err;
if (err !== 'timeout')
throw err;
});
}
waitFor.assert = function(fn, timeout) {
var lastError;
return waitFor(function() {
try {
var result = fn();
if (isPromise(result)) {
return Promise.resolve(result).then(function() {
return true;
});
} else {
return true;
}
} catch (e) {
lastError = e;
return false;
}
}, timeout).catch(function (err) {
return Promise.reject(lastError);
});
};
waitFor.assertHold = function(fn, timeout) {
var elapsed = 0;
return new Promise(function(resolve, reject) {
function recur() {
try {
fn();
} catch (err) {
return reject(err);
}
if (elapsed > timeout)
return resolve();
setTimeout(function () {
elapsed += 10;
recur();
}, 10);
}
recur();
});
};
function waitPromise(delay) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(delay);
}, delay);
});
}
function isPromise(value) {
return typeof(value && value.then) === 'function';
}
module.exports = waitFor;