import { describe, it, expect } from "vitest"; import { errorResponse } from "./apiRoute"; import type { ApiResult } from "@/app/lib/types"; function failure(overrides: Partial, { ok: false }>>): Extract< ApiResult, { ok: false } > { return { ok: false, error: "boom", ...overrides }; } describe("errorResponse", () => { it("returns 401 when the result is marked expired, regardless of status", async () => { const res = errorResponse(failure({ expired: true, status: 404 })); expect(res.status).toBe(401); }); it("forwards a genuine 404 upstream status", async () => { const res = errorResponse(failure({ status: 404 })); expect(res.status).toBe(404); expect((await res.json()).error).toBe("boom"); }); it("forwards a genuine 403 upstream status", async () => { const res = errorResponse(failure({ status: 403 })); expect(res.status).toBe(403); }); it("forwards an upstream machine-readable code", async () => { const res = errorResponse(failure({ status: 403, code: "PASSWORD_RESET_REQUIRED" })); expect(await res.json()).toEqual({ error: "boom", code: "PASSWORD_RESET_REQUIRED" }); }); it("forwards a genuine 409 upstream status", async () => { const res = errorResponse(failure({ status: 409 })); expect(res.status).toBe(409); }); it("falls back to 400 when the upstream status is a 5xx", async () => { const res = errorResponse(failure({ status: 500 })); expect(res.status).toBe(400); }); it("falls back to 400 when no upstream status is present", async () => { const res = errorResponse(failure({})); expect(res.status).toBe(400); }); }); describe("errorResponse — error list (add-shipping-rates)", () => { it("includes the error list when the result carries one", async () => { const res = errorResponse({ ok: false, status: 400, error: "Rates not saved", errors: ["Row 3: gap after 1 kg"] }); expect(res.status).toBe(400); expect(await res.json()).toEqual({ error: "Rates not saved", errors: ["Row 3: gap after 1 kg"] }); }); }); describe("errorResponse — coded details", () => { it("includes the details with the code when the result carries them", async () => { const res = errorResponse({ ok: false, status: 400, error: "Insufficient stock", code: "INSUFFICIENT_STOCK", details: { skuVariationId: 50, available: 0, requested: 10 }, }); expect(res.status).toBe(400); expect(await res.json()).toEqual({ error: "Insufficient stock", code: "INSUFFICIENT_STOCK", details: { skuVariationId: 50, available: 0, requested: 10 }, }); }); it("adds no details key when the result carries none", async () => { const res = errorResponse({ ok: false, status: 400, error: "boom" }); expect(await res.json()).not.toHaveProperty("details"); }); });