-
Notifications
You must be signed in to change notification settings - Fork 235
/
http_server_node.test.ts
112 lines (100 loc) · 2.56 KB
/
http_server_node.test.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Copyright 2018-2024 the oak authors. All rights reserved. MIT license.
// deno-lint-ignore-file no-explicit-any
import { assertEquals, unreachable } from "./deps_test.ts";
import {
type IncomingMessage,
NodeRequest,
Server,
type ServerResponse,
} from "./http_server_node.ts";
import { Application } from "./application.ts";
const destroyCalls: any[][] = [];
const setHeaderCalls: any[][] = [];
const writeCalls: any[][] = [];
const writeHeadCalls: any[][] = [];
function createMockReqRes(
url = "/",
headers: Record<string, string> = {},
method = "GET",
address = "127.0.0.1",
): [req: IncomingMessage, res: ServerResponse] {
destroyCalls.length = 0;
setHeaderCalls.length = 0;
writeCalls.length = 0;
writeHeadCalls.length = 0;
const req = {
headers,
method,
socket: {
address() {
return {
addr: {
address,
},
};
},
},
url,
on(_method: string, _listener: (arg?: any) => void) {},
};
const res = {
destroy(...args: any[]) {
destroyCalls.push(args);
},
end(callback?: () => void) {
if (callback) {
callback();
}
},
setHeader(...args: any[]) {
setHeaderCalls.push(args);
},
write(chunk: unknown, callback?: (err: Error | null) => void) {
writeCalls.push([chunk, callback]);
if (callback) {
callback(null);
}
},
writeHead(...args: any[]) {
writeHeadCalls.push(args);
},
};
return [req, res];
}
Deno.test({
name: "NodeRequest",
async fn() {
const nodeRequest = new NodeRequest(
...createMockReqRes("/", {}, "POST", "127.0.0.1"),
);
assertEquals(nodeRequest.url, `/`);
const response = new Response("hello deno");
await nodeRequest.respond(response);
assertEquals(writeHeadCalls, [[200, ""]]);
},
});
Deno.test({
name: "HttpServer closes gracefully after serving requests",
// TODO(@kitsonk) this is failing locally for me, figure out what is wrong.
ignore: true,
async fn() {
const app = new Application();
const listenOptions = { port: 4508 };
const server = new Server(app, listenOptions);
await server.listen();
const expectedBody = "test-body";
(async () => {
for await (const nodeRequest of server) {
nodeRequest.respond(new Response(expectedBody));
}
})();
try {
const response = await fetch(`http://localhost:${listenOptions.port}`);
assertEquals(await response.text(), expectedBody);
} catch {
unreachable();
} finally {
server.close();
}
},
});