-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathapi.test.js
86 lines (74 loc) · 2.24 KB
/
api.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
const test = require('ava')
const safeAwait = require('../lib')
test('Valid promise has data. [err, data]', async (t) => {
const [err, data] = await safeAwait(promiseOne())
t.is(err, undefined)
t.is(data, 'data here')
})
test('Error promise has string error. [err, data]', async (t) => {
const [err, data] = await safeAwait(promiseOne(true))
t.is(err, 'error happened')
t.is(data, undefined)
})
test('Error promise has instance of error. [err, data]', async (t) => {
const [err, data] = await safeAwait(promiseThrows())
t.is(err instanceof Error, true)
t.is(data, undefined)
})
/**
* Verify promises still throw native errors when deeper issue exists
*/
test('throws on code syntax error "ReferenceError"', async t => {
await t.throwsAsync(async () => {
const [err, data] = await safeAwait(promiseWithSyntaxError())
}, {
instanceOf: ReferenceError,
message: 'madeUpThing is not defined'
})
})
test('throws on code syntax error "ReferenceError" in try/catch', async t => {
try {
const [err, data] = await safeAwait(promiseWithSyntaxError())
} catch (e) {
t.is(e instanceof ReferenceError, true)
}
})
test('throws on code "TypeError"', async t => {
await t.throwsAsync(async () => {
const [err, data] = await safeAwait(promiseWithTypeError())
}, {
instanceOf: TypeError,
message: 'Cannot read property \'lolCool\' of null'
})
})
test('throws on code "TypeError" in try/catch', async t => {
try {
const [err, data] = await safeAwait(promiseWithTypeError())
} catch (e) {
t.is(e instanceof TypeError, true)
}
})
function promiseOne(doError) {
return new Promise((resolve, reject) => {
if (doError) return reject('error happened') // eslint-disable-line
return resolve('data here')
})
}
function promiseThrows(doError) {
return new Promise((resolve, reject) => {
return reject(new Error('business logic error'))
})
}
function promiseWithSyntaxError(doError) {
return new Promise((resolve, reject) => {
console.log(madeUpThing)
return resolve('should not reach this')
})
}
function promiseWithTypeError(doError) {
return new Promise((resolve, reject) => {
const fakeObject = null
console.log(fakeObject.lolCool)
return resolve('should not reach this')
})
}