-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.test.js
77 lines (58 loc) · 1.49 KB
/
index.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
const {
first, last, distinct, deeplyDistinct,
} = require('.');
const cancel = require('./cancel');
const createMockFn = (errorIdx = []) => {
let counter = 0;
const fn = async (delay, val) => {
await new Promise(r => setTimeout(r, delay));
if (errorIdx.includes(counter++)) {
throw val;
}
return val;
};
return fn;
};
test('last', async () => {
const successVals = [];
const fn = createMockFn();
const lastFn = last(fn, (r) => successVals.push(r));
await Promise.all([
lastFn(100, 1),
lastFn(200, 2),
lastFn(150, 3),
]);
expect(successVals).toEqual([3]);
});
test('first', async () => {
const successVals = [];
const fn = createMockFn();
const lastFn = first(fn, (r) => successVals.push(r));
const a = lastFn(150, 1);
const b = lastFn(200, 2);
const c = lastFn(100, 3);
await a;
expect(successVals).toEqual([1]);
expect(b instanceof Promise).toBe(false);
expect(c instanceof Promise).toBe(false);
});
test('distinct', async () => {
const vals = [];
const fn = createMockFn();
const lastFn = distinct(fn, (r) => vals.push(r));
const a = lastFn(150, 1);
const b = lastFn(150, 1);
const c = lastFn(200, 2);
const d = lastFn(200, 2);
await Promise.all([a, c]);
expect(vals).toEqual([2]);
expect(b instanceof Promise).toBe(false);
expect(d instanceof Promise).toBe(false);
});
test('cancel token', async () => {
const vals = [];
const fn = createMockFn();
const lastFn = last(fn, (r) => vals.push(r));
await lastFn(150, cancel);
expect(vals).toEqual([]);
});