Skip to content

Commit 86342d1

Browse files
authored
Add test for defaeult handler (#15258)
1 parent d4f3726 commit 86342d1

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import { createMocks } from "node-mocks-http";
2+
import { describe, it, expect, vi, afterEach } from "vitest";
3+
4+
import { defaultHandler } from "./defaultHandler";
5+
6+
describe("defaultHandler Test Suite", () => {
7+
afterEach(() => {
8+
vi.clearAllMocks();
9+
});
10+
11+
it("should return 405 for unsupported HTTP methods", async () => {
12+
const handlers = {};
13+
const handler = defaultHandler(handlers);
14+
15+
const { req, res } = createMocks({
16+
method: "PATCH", // Unsupported method here
17+
});
18+
19+
await handler(req, res);
20+
21+
expect(res._getStatusCode()).toBe(405);
22+
expect(res._getJSONData()).toEqual({
23+
message: "Method Not Allowed (Allow: )",
24+
});
25+
});
26+
27+
it("should call the correct handler for a supported method", async () => {
28+
const getHandler = vi.fn().mockResolvedValue(null);
29+
const handlers = {
30+
GET: { default: getHandler },
31+
};
32+
const handler = defaultHandler(handlers);
33+
34+
const { req, res } = createMocks({
35+
method: "GET",
36+
});
37+
38+
await handler(req, res);
39+
40+
expect(getHandler).toHaveBeenCalledWith(req, res);
41+
});
42+
43+
it("should return 500 for errors thrown in handler", async () => {
44+
const getHandler = vi.fn().mockRejectedValue(new Error("Test Error"));
45+
const handlers = {
46+
GET: { default: getHandler },
47+
};
48+
const handler = defaultHandler(handlers);
49+
50+
const { req, res } = createMocks({
51+
method: "GET",
52+
});
53+
54+
await handler(req, res);
55+
56+
expect(res._getStatusCode()).toBe(500);
57+
expect(res._getJSONData()).toEqual({
58+
message: "Something went wrong",
59+
});
60+
});
61+
});

0 commit comments

Comments
 (0)