-
Notifications
You must be signed in to change notification settings - Fork 2
/
api.spec.ts
107 lines (96 loc) · 2.82 KB
/
api.spec.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
import * as http from "node:http";
import { handleApi } from "./api";
jest.mock("~/utils/filesys", () => ({
walkTree: () => {
return [];
},
matchPath: () => {
return { path: "/path/to/", name: "api-file.ts" };
},
}));
describe("utils/callback/api.ts", () => {
describe("handleApi", () => {
const exampleRequest = {
method: "GET",
url: "/",
path: "/",
body: "",
headers: {},
captureLogs: true,
};
afterEach(() => {
jest.resetModules();
});
describe("with returned object", () => {
beforeEach(() => {
jest.mock(
"/path/to/api-file.ts",
() => ({
default: () => {
console.info("this is an info");
console.log("this info log should be captured");
console.info("this is another info");
console.error("this error log should be captured");
process.stdout.write("this comes from process.stdout.write");
return {
body: "Hello world",
status: 201,
headers: {
"X-Custom-Header": "Sample Project",
},
};
},
}),
{ virtual: true }
);
});
test("should handle returning a response body", async () => {
const response = await handleApi(exampleRequest, "/");
const expectedLogs =
"stdout:this is an info\n" +
"stdout:this info log should be captured\n" +
"stdout:this is another info\n" +
"stderr:this error log should be captured\n" +
"stdout:this comes from process.stdout.write";
expect(response).toEqual({
body: "Hello world",
status: 201,
logs: expectedLogs,
headers: {
"X-Custom-Header": "Sample Project",
},
});
});
});
describe("with response.end", () => {
beforeEach(() => {
jest.mock(
"/path/to/api-file.ts",
() => ({
default: (_: http.IncomingMessage, res: http.ServerResponse) => {
console.log("captured logs");
res.setHeader("X-Custom-Header", "Sample Project");
res.write("Hi world");
res.end();
},
}),
{ virtual: true }
);
});
test("should handle returning a response body", async () => {
const response = await handleApi(exampleRequest, "/");
expect(response).toEqual({
buffer: "SGkgd29ybGQ=",
status: 200,
statusMessage: "OK",
logs: "stdout:captured logs\n",
headers: {
connection: "close",
date: expect.any(String),
"x-custom-header": "Sample Project",
},
});
});
});
});
});