1 import { describe, expect, test, vi } from "vitest"
2 import {
3 RouteError,
4 throwErrorResponse,
5 withRouteErrorHandling,
6 } from "../route-error.js"
7
8 describe("withRouteErrorHandling", () => {
9 test("returns the handler's response when nothing throws", async () => {
10 const handler = withRouteErrorHandling(async () =>
11 Response.json({ ok: true })
12 )
13
14 const res = await handler()
15
16 expect(res.status).toBe(200)
17 expect(await res.json()).toEqual({ ok: true })
18 })
19
20 test("converts a thrown error response to JSON with its status", async () => {
21 const handler = withRouteErrorHandling(async () => {
22 throwErrorResponse(404, "Spec not found")
23 return new Response()
24 })
25
26 const res = await handler()
27
28 expect(res.status).toBe(404)
29 expect(res.headers.get("Content-Type")).toBe("application/json")
30 expect(await res.json()).toEqual({
31 error: {
32 status: 404,
33 name: "NotFound",
34 message: "Spec not found",
35 },
36 })
37 })
38
39 test("uses a custom error name when passed", async () => {
40 const handler = withRouteErrorHandling(async () => {
41 throwErrorResponse(418, "Nope", "Teapot")
42 return new Response()
43 })
44
45 expect(await (await handler()).json()).toEqual({
46 error: { status: 418, name: "Teapot", message: "Nope" },
47 })
48 })
49
50 test("converts an unexpected error to a 500 JSON response", async () => {
51 const consoleError = vi.spyOn(console, "error").mockImplementation(() => {})
52 const handler = withRouteErrorHandling(async () => {
53 throw new Error("boom")
54 })
55
56 const res = await handler()
57
58 expect(res.status).toBe(500)
59 expect(await res.json()).toEqual({
60 error: {
61 status: 500,
62 name: "InternalServerError",
63 message: "boom",
64 },
65 })
66 consoleError.mockRestore()
67 })
68
69 test("passes the handler's arguments through", async () => {
70 const handler = withRouteErrorHandling(
71 async (request: Request, ctx: { params: Promise<{ id: string }> }) =>
72 Response.json({
73 url: request.url,
74 id: (await ctx.params).id,
75 })
76 )
77
78 const res = await handler(new Request("https://docs.medusajs.com/x"), {
79 params: Promise.resolve({ id: "1" }),
80 })
81
82 expect(await res.json()).toEqual({
83 url: "https://docs.medusajs.com/x",
84 id: "1",
85 })
86 })
87 })
88
89 describe("RouteError", () => {
90 test("falls back to a generic name for unmapped statuses", () => {
91 expect(new RouteError(499, "closed").body).toEqual({
92 error: { status: 499, name: "Error", message: "closed" },
93 })
94 })
95 })