forked from Lilly-Protocol/lily-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.middleware.test.ts
More file actions
46 lines (41 loc) · 1.71 KB
/
Copy patherror.middleware.test.ts
File metadata and controls
46 lines (41 loc) · 1.71 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
import express from "express";
import request from "supertest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { AppError } from "../src/common/http/app-error";
import { errorHandler } from "../src/common/http/error.middleware";
import { logger } from "../src/config/logger";
describe("error middleware logging", () => {
afterEach(() => vi.restoreAllMocks());
it.each([
[new AppError(400, "Bad request", { field: "name" }), 400, "warn"],
[new AppError(404, "Not found"), 404, "warn"],
[new AppError(429, "Too many requests"), 429, "warn"],
[new AppError(500, "Internal failure"), 500, "error"],
[new AppError(503, "Unavailable"), 503, "error"],
[new Error("Unexpected failure"), 500, "error"],
] as const)("logs %s at %s using %s", async (error, statusCode, level) => {
const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
const errorLog = vi.spyOn(logger, "error").mockImplementation(() => {});
const app = express();
app.get("/failure", () => {
throw error;
});
app.use(errorHandler);
const response = await request(app).get("/failure?source=test");
expect(response.status).toBe(statusCode);
expect(response.body).toMatchObject({
success: false,
message: error.message,
});
if (error instanceof AppError && error.details) {
expect(response.body.details).toEqual(error.details);
}
const selected = level === "warn" ? warn : errorLog;
const other = level === "warn" ? errorLog : warn;
expect(selected).toHaveBeenCalledExactlyOnceWith(
{ err: error, method: "GET", path: "/failure?source=test", statusCode },
"Request failed",
);
expect(other).not.toHaveBeenCalled();
});
});