-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathTestServer.ts
More file actions
83 lines (70 loc) · 2.11 KB
/
TestServer.ts
File metadata and controls
83 lines (70 loc) · 2.11 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
80
81
82
83
import { AxiosInstance } from 'axios'
import getPort from 'get-port'
import http from 'http'
import { TracedTestRequest } from './TracedTestRequest'
type ExpectFn = (req: http.IncomingMessage, res: http.ServerResponse) => Promise<void> | void
interface TestRequestArgs {
params: Record<string, any>
url?: string
retries?: number
timeout?: number
baseURL?: string
}
export class TestServer {
public static async getAndStartTestServer() {
const port = await getPort({ port: [3000, 3001, 3002, 3003] })
const testServer = new TestServer(port)
testServer.startServer()
return testServer
}
private server: http.Server
private expectFn: ExpectFn
private responseHeaders: Record<string, string>
constructor(private port: number) {
// tslint:disable-next-line
this.expectFn = () => {}
this.responseHeaders = {}
this.server = http.createServer(async (req, res) => {
this.setHeaders(res)
await this.expectFn(req, res)
if (!res.writableEnded) {
res.end()
}
})
}
public setExpectFn(expectFn: ExpectFn) {
this.expectFn = expectFn
}
public startServer() {
console.log(`Starting test server on port ${this.port}...`)
this.server.listen(this.port)
}
public closeServer() {
console.log('Closing test server...')
return new Promise((resolve, reject) => {
this.server.close(err => {
if (err) {
return reject(err)
}
resolve(undefined)
})
})
}
public getUrl(path = '') {
return `http://localhost:${this.port}${path}`
}
public mockResponseHeaders(headers: Record<string, string>) {
this.responseHeaders = headers
}
public async doRequest(client: AxiosInstance, reqArgs?: TestRequestArgs) {
const url = reqArgs?.url ?? this.getUrl()
const tracedTestRequest = new TracedTestRequest(client)
await tracedTestRequest.runRequest({ ...reqArgs, url })
return tracedTestRequest
}
private setHeaders(response: http.ServerResponse) {
Object.keys(this.responseHeaders).forEach(header => {
response.setHeader(header, this.responseHeaders[header])
})
}
}