-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathcapturingHttpProxy.test.ts
More file actions
74 lines (65 loc) · 2.19 KB
/
Copy pathcapturingHttpProxy.test.ts
File metadata and controls
74 lines (65 loc) · 2.19 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
import http from "http";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { CapturedExchange, CapturingHttpProxy } from "./capturingHttpProxy";
describe("Capturing HTTP Proxy", () => {
let proxy: CapturingHttpProxy;
let testServer: http.Server;
let testServerAddress: string;
beforeEach(async () => {
testServer = http.createServer((req, res) => {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ message: "Hello", path: req.url }));
});
await new Promise<void>((resolve, reject) => {
testServer.listen(0, "127.0.0.1", () => {
const addr = testServer.address();
if (addr instanceof Object) {
testServerAddress = `http://${addr.address}:${addr.port}`;
resolve();
} else {
reject(new Error("Failed to get test server address"));
}
});
});
});
afterEach(async () => {
if (proxy) {
await proxy.stop();
}
if (testServer) {
await new Promise<void>((resolve, reject) =>
testServer.close((err) => {
if (err) {
reject(err);
} else {
resolve();
}
}),
);
}
});
test("captures HTTP requests and responses", async () => {
proxy = new CapturingHttpProxy(testServerAddress);
const proxyUrl = await proxy.start();
const response = await fetch(`${proxyUrl}/api/test`);
expect(response.status).toBe(200);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const data = await response.json();
expect(data).toEqual({ message: "Hello", path: "/api/test" });
expect(proxy.exchanges).toMatchObject([
{
request: {
url: "/api/test",
method: "GET",
},
response: {
statusCode: 200,
body: JSON.stringify({ message: "Hello", path: "/api/test" }),
},
} as CapturedExchange,
]);
});
});