forked from Lilly-Protocol/lily-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.test.ts
More file actions
62 lines (57 loc) · 1.96 KB
/
Copy patherrors.test.ts
File metadata and controls
62 lines (57 loc) · 1.96 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
import { describe, it, expect } from "vitest";
import { LilyApiError, isLilyApiError, handleApiResponse } from "./errors";
describe("LilyApiError", () => {
it("stores status, code, message and details", () => {
const err = new LilyApiError("Not found", 404, "NOT_FOUND", [
{ field: "id", reason: "missing" },
]);
expect(err).toBeInstanceOf(Error);
expect(err.status).toBe(404);
expect(err.code).toBe("NOT_FOUND");
expect(err.message).toBe("Not found");
expect(err.details).toHaveLength(1);
});
it("is detected by type guard", () => {
const err = new LilyApiError("fail", 500, "INTERNAL");
expect(isLilyApiError(err)).toBe(true);
expect(isLilyApiError(new Error("x"))).toBe(false);
});
});
describe("handleApiResponse", () => {
it("does nothing for ok responses", async () => {
await expect(
handleApiResponse(new Response(null, { status: 200 })),
).resolves.toBeUndefined();
});
it("maps JSON error body to LilyApiError", async () => {
const res = new Response(
JSON.stringify({ code: "VALIDATION", message: "Bad input", details: [] }),
{ status: 422, statusText: "Unprocessable Entity" },
);
try {
await handleApiResponse(res);
expect.fail("should throw");
} catch (e) {
expect(isLilyApiError(e)).toBe(true);
if (isLilyApiError(e)) {
expect(e.status).toBe(422);
expect(e.code).toBe("VALIDATION");
expect(e.message).toBe("Bad input");
}
}
});
it("falls back to status text when body is not JSON", async () => {
const res = new Response("nope", { status: 503, statusText: "Service Unavailable" });
try {
await handleApiResponse(res);
expect.fail("should throw");
} catch (e) {
expect(isLilyApiError(e)).toBe(true);
if (isLilyApiError(e)) {
expect(e.status).toBe(503);
expect(e.code).toBe("UNKNOWN_ERROR");
expect(e.message).toBe("Service Unavailable");
}
}
});
});