blob: 131c1778860580c9613851c201ce611f5bd3d398 (
plain) (
blame)
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
|
var http = require('http');
var url = require('url');
var handlers = require('./handlers');
class MockServer {
constructor() {
this.handlers = [];
this.server = undefined;
}
start() {
if (this.server) {
throw new Error('Server is already started');
}
let listener = (req, res) => {
if (req.method !== 'GET') {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('not found')
return
}
let u = url.parse(req.url);
let handler = this.handlers.find(h => u.pathname == h.pathname);
if (!handler) {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('not found')
return
}
handler.handler(req, res);
}
this.server = http.createServer(listener);
this.server.listen();
}
stop() {
if (!this.server) {
throw new Error('Server is not started');
}
this.server.close();
this.server = undefined;
}
port() {
if (!this.server) {
throw new Error('Server is not started');
}
return this.server.address().port
}
on(pathname, handler) {
this.handlers.push({ pathname, handler });
}
}
module.exports = MockServer
|