/
with-server.ts
76 lines (59 loc) 路 1.78 KB
/
with-server.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
import {promisify} from 'util';
import http = require('http');
import tempy = require('tempy');
import createTestServer = require('create-test-server');
import lolex = require('lolex');
import got from '../../source';
const generateHook = ({install}) => async (t, run) => {
const clock = install ? lolex.install() : lolex.createClock();
// @ts-ignore
const server = await createTestServer({
bodyParser: {
type: () => false
}
});
const options = {
avaTest: t.title,
handlers: [
(options, next) => {
const result = next(options);
clock.tick(0);
result.on('response', () => {
clock.tick(0);
});
return result;
}
]
};
// @ts-ignore Ignore errors for extending got, for the tests
const preparedGot = got.extend({prefixUrl: server.url, ...options});
// @ts-ignore Ignore errors for extending got, for the tests
preparedGot.secure = got.extend({prefixUrl: server.sslUrl, ...options});
server.hostname = (new URL(server.url)).hostname;
server.sslHostname = (new URL(server.sslUrl)).hostname;
try {
await run(t, server, preparedGot, clock);
} finally {
await server.close();
}
if (install) {
// @ts-ignore This is a global clock.
clock.uninstall();
}
};
export default generateHook({install: false});
export const withServerAndLolex = generateHook({install: true});
// TODO: remove this when `create-test-server` supports custom listen
export const withSocketServer = async (t, run) => {
const socketPath = tempy.file({extension: 'socket'});
const server = http.createServer((request, response) => {
server.emit(request.url, request, response);
}) as any;
server.socketPath = socketPath;
await promisify(server.listen.bind(server))(socketPath);
try {
await run(t, server);
} finally {
await promisify(server.close.bind(server))();
}
};