-
Notifications
You must be signed in to change notification settings - Fork 1
/
async-helper-sequecne.test.js
43 lines (39 loc) · 1.11 KB
/
async-helper-sequecne.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
function sequence(tasks) {
return new Promise((resolve, reject) => {
let index = 0;
function resolveTask(prevResult = null) {
if(index >= tasks.length) {
resolve(prevResult);
return;
}
const task = tasks[index];
task(prevResult).then(res => {
index ++;
resolveTask(res);
}).catch(err => {
reject(err)
});
}
resolveTask();
});
}
describe("Async helper sequence() unit tests", () => {
beforeEach(() => {});
it("Should resolve with correct result from list of tasks", async() => {
const tasks = [
() => Promise.resolve(1),
(prevResult) => Promise.resolve(prevResult + 2),
(prevResult) => Promise.resolve(prevResult + 3),
];
const results = await sequence(tasks);
expect(results).toEqual(6);
});
it("Should reject if any tasks gets rejected", async() => {
const tasks = [
() => Promise.resolve(1),
(prevResult) => Promise.reject(new Error('failed')),
(prevResult) => Promise.resolve(prevResult + 3),
];
await expect(sequence(tasks)).rejects.toThrow('failed');
});
});