-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
test.js
133 lines (110 loc) · 2.25 KB
/
test.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
import test from 'ava';
import pWhilst from './index.js';
test('main', async t => {
const result = [];
let counter = 0;
await pWhilst(
() => result.length < 7,
() => {
result.push(counter++);
},
);
t.is(counter, 7);
t.deepEqual(result, [0, 1, 2, 3, 4, 5, 6]);
});
test('calling sequence is correct', async t => {
const sequence = [];
let counter = 0;
await pWhilst(
() => {
sequence.push(`predicate${counter}`);
return counter < 2;
},
() => {
sequence.push(`action${counter}`);
counter++;
},
);
t.is(counter, 2);
t.deepEqual(sequence, [
'predicate0',
'action0',
'predicate1',
'action1',
'predicate2',
]);
});
test('condition receives action result', async t => {
const result = [];
await pWhilst(
input => input === undefined || input.length < 7,
() => {
result.push(result.length);
return result;
},
);
t.deepEqual(result, [0, 1, 2, 3, 4, 5, 6]);
});
test('works with action returning a promise', async t => {
const result = [];
let counter = 0;
await pWhilst(
() => result.length < 7,
() =>
new Promise(resolve => {
result.push(counter++);
resolve();
}),
);
t.is(counter, 7);
t.deepEqual(result, [0, 1, 2, 3, 4, 5, 6]);
});
test('stops on error', async t => {
const result = [];
let counter = 0;
const promise = pWhilst(
() => result.length < 10,
() =>
new Promise(resolve => {
if (counter === 7) {
throw new Error('BAAD');
}
result.push(counter++);
resolve();
}),
);
await t.throwsAsync(promise, {message: 'BAAD'});
t.is(counter, 7);
t.deepEqual(result, [0, 1, 2, 3, 4, 5, 6]);
});
test('works with condition returning a promise', async t => {
const result = [];
let counter = 0;
const checkServer = () =>
new Promise(resolve => {
setTimeout(() => {
resolve(counter < 7);
}, 10);
});
await pWhilst(
() => checkServer(),
() => {
result.push(counter++);
},
);
t.is(counter, 7);
t.deepEqual(result, [0, 1, 2, 3, 4, 5, 6]);
});
test('accepts an initial value', async t => {
const result = [];
const counter = await pWhilst(
async () => result.length < 7,
async currentCount => {
result.push(currentCount);
return currentCount + 1;
},
2,
);
t.is(counter, 9);
t.deepEqual(result, [2, 3, 4, 5, 6, 7, 8]);
});