-
-
Notifications
You must be signed in to change notification settings - Fork 916
/
hooks.js
105 lines (97 loc) 路 1.7 KB
/
hooks.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import test from 'ava';
import delay from 'delay';
import {createServer} from './helpers/server';
import got from '..';
let s;
test.before('setup', async () => {
s = await createServer();
const echoHeaders = (req, res) => {
res.statusCode = 200;
res.write(JSON.stringify(req.headers));
res.end();
};
s.on('/', echoHeaders);
await s.listen(s.port);
});
test('beforeRequest receives normalized options', async t => {
await got(
s.url,
{
json: true,
hooks: {
beforeRequest: [
options => {
t.is(options.path, '/');
t.is(options.hostname, 'localhost');
}
]
}
}
);
});
test('beforeRequest allows modifications', async t => {
const res = await got(
s.url,
{
json: true,
hooks: {
beforeRequest: [
options => {
options.headers.foo = 'bar';
}
]
}
}
);
t.is(res.body.foo, 'bar');
});
test('beforeRequest awaits async function', async t => {
const res = await got(
s.url,
{
json: true,
hooks: {
beforeRequest: [
async options => {
await delay(100);
options.headers.foo = 'bar';
}
]
}
}
);
t.is(res.body.foo, 'bar');
});
test('beforeRequest rejects when beforeRequest throws', async t => {
await t.throws(
() => got(s.url, {
hooks: {
beforeRequest: [
() => {
throw new Error('oops');
}
]
}
}),
{
instanceOf: Error,
message: 'oops'
}
);
});
test('beforeRequest rejects when beforeRequest rejects', async t => {
await t.throws(
() => got(s.url, {
hooks: {
beforeRequest: [() => Promise.reject(new Error('oops'))]
}
}),
{
instanceOf: Error,
message: 'oops'
}
);
});
test.after('cleanup', async () => {
await s.close();
});