-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathtest-http-server.js
More file actions
79 lines (63 loc) · 1.7 KB
/
test-http-server.js
File metadata and controls
79 lines (63 loc) · 1.7 KB
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
'use strict';
const express = require('express');
const request = require('request-promise');
let serverID = 0;
class TestHTTPServer {
constructor(middleware, options) {
this.options = options || {};
this.middleware = middleware;
this.listener = null;
this.id = ++serverID;
}
start() {
let options = this.options;
let app = express();
app.get('/*', this.middleware);
if (options.errorHandling) {
app.use((err, req, res, next) => {
res.set('x-test-error', 'error handler called');
next(err);
});
}
if (options.recoverErrors) {
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
res.set('x-test-recovery', 'recovered response');
res.status(200);
res.send('hello world');
});
}
return new Promise((resolve) => {
let port = options.port || 3000;
let host = options.host || 'localhost';
let listener = app.listen(port, host, () => {
let host = listener.address().address;
let port = listener.address().port;
this.listener = listener;
this.info = {
host: host,
port: port,
listener: listener,
};
resolve(this.info);
});
});
}
request(urlPath, options) {
let info = this.info;
let url = 'http://[' + info.host + ']:' + info.port;
if (options && options.resolveWithFullResponse) {
return request({
resolveWithFullResponse: options.resolveWithFullResponse,
uri: url + urlPath,
});
}
return request(url + urlPath);
}
stop() {
if (this.listener) {
this.listener.close();
}
}
}
module.exports = TestHTTPServer;