-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
async-iterator.spec.ts
100 lines (80 loc) · 1.85 KB
/
async-iterator.spec.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
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
import {
mapAsyncIterator,
combineAsyncIterators,
tapAsyncIterator,
} from './async-iterator';
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
describe('combineAsyncIterators', () => {
it('should merge iterators', async () => {
async function* a() {
await delay(20);
yield 'a';
}
async function* b() {
await delay(0);
yield 'b';
}
const c = combineAsyncIterators(a(), b());
const results = [];
for await (const x of c) {
results.push(x);
}
expect(results).toEqual(['b', 'a']);
});
it('should throw when one iterator throws', async () => {
async function* a() {
await delay(20);
yield 'a';
}
async function* b() {
throw new Error('threw in b');
}
const c = combineAsyncIterators(a(), b());
async function* d() {
yield* c;
}
try {
for await (const x of d()) {
}
throw new Error('should not reach here');
} catch (e) {
expect(e.message).toMatch(/threw in b/);
}
});
});
describe('mapAsyncIterator', () => {
it('should map over values', async () => {
async function* f() {
yield 1;
yield 2;
yield 3;
}
const c = mapAsyncIterator(f(), (x) => x * 2);
const results = [];
for await (const x of c) {
results.push(x);
}
expect(results).toEqual([2, 4, 6]);
});
});
describe('tapAsyncIterator', () => {
it('should tap values', async () => {
async function* f() {
yield 1;
yield 2;
yield 3;
}
const tapped = [];
const results = [];
const c = tapAsyncIterator(f(), (x) => {
tapped.push(`tap: ${x}`);
});
for await (const x of c) {
results.push(x);
}
expect(tapped).toEqual(['tap: 1', 'tap: 2', 'tap: 3']);
expect(results).toEqual([1, 2, 3]);
});
});