-
Notifications
You must be signed in to change notification settings - Fork 20
/
79-promise-catch.js
85 lines (68 loc) · 2.32 KB
/
79-promise-catch.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
// 79: Promise - catch
// To do: make all tests pass, leave the assert lines unchanged!
// Here we use promises to trigger, don't modify the block with the
// returning promise!
describe('`catch()` returns a Promise and deals with rejected cases only', () => {
describe('prerequisites for understanding', () => {
it('*return* a fulfilled promise, to pass a test', () => {
return Promise.resolve();
assert(false); // Don't touch! Make the test pass in the line above!
});
it('reminder: the test passes when a fulfilled promise is returned', () => {
return Promise.resolve('I should fulfill.');
});
});
describe('`catch` method basics', () => {
it('is an instance method', () => {
const p = Promise.resolve();
assert.equal(typeof p.catch, 'function');
});
it('catches only promise rejections', (done) => {
const promise = Promise.reject();
promise
.then(() => { done('Should not be called!'); })
.catch(done);
});
it('returns a new promise', () => {
const whatToReturn = () => Promise.resolve();
const promise = Promise.reject();
return promise.catch(() =>
whatToReturn()
);
});
it('converts it`s return value into a promise', () => {
const p = Promise.reject();
const p1 = p.catch(() => 'promise?');
return p1.then(result => assert.equal('promise?', result));
});
it('the first parameter is the rejection reason', () => {
const p = Promise.reject('oops');
return p.catch(reason => {
assert.equal(reason, 'oops');
});
});
});
describe('multiple `catch`es', () => {
it('only the first `catch` is called', () => {
const p = Promise.reject('1');
const p1 = p
.catch(reason => `${reason} AND 2`)
.catch(reason => `${reason} AND 3`)
;
return p1.then(result =>
assert.equal(result, '1 AND 2')
);
});
it('if a `catch` throws, the next `catch` catches it', () => {
const p = Promise.reject('1');
const p1 = p
.catch(reason => { throw Error(`${reason} AND 2`) })
.catch(err => { throw Error(`${err.message} AND 3`) })
.catch(err => err.message)
;
return p1.then(result =>
assert.equal(result, '1 AND 2 AND 3')
);
});
});
});