import { describe, it, expect, vi, beforeEach } from "vitest"; const mocks = vi.hoisted(() => ({ callMobileApiBinary: vi.fn(), getToken: vi.fn() })); vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApiBinary: mocks.callMobileApiBinary })); vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); import { GET } from "./route"; type Req = Parameters[0]; const req = (url: string) => new Request(`http://localhost${url}`) as unknown as Req; beforeEach(() => { mocks.callMobileApiBinary.mockReset(); mocks.getToken.mockReset().mockResolvedValue("jwt-abc"); }); describe("/api/leads/export", () => { it("returns 401 without a session", async () => { mocks.getToken.mockResolvedValue(null); expect((await GET(req("/api/leads/export"))).status).toBe(401); expect(mocks.callMobileApiBinary).not.toHaveBeenCalled(); }); it("forwards the query string and passes bytes and headers through", async () => { mocks.callMobileApiBinary.mockResolvedValue({ ok: true, data: { body: new Uint8Array([1, 2, 3]).buffer, contentType: "application/x-xlsx", contentDisposition: 'attachment; filename="l.xlsx"' } }); const res = await GET(req("/api/leads/export?q=ann")); expect(mocks.callMobileApiBinary).toHaveBeenCalledWith("/api/admin/leads/export?q=ann", { token: "jwt-abc", timeoutMs: 120_000 }); // design: the export route waits up to 120 s expect(res.status).toBe(200); expect(res.headers.get("content-type")).toBe("application/x-xlsx"); expect(res.headers.get("content-disposition")).toBe('attachment; filename="l.xlsx"'); expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([1, 2, 3])); }); it("maps a failure through errorResponse, keeping code and details", async () => { mocks.callMobileApiBinary.mockResolvedValue({ ok: false, error: "Too many", status: 422, code: "EXPORT_TOO_LARGE", details: { limit: 20000 } }); const res = await GET(req("/api/leads/export")); expect(res.status).toBe(422); expect(await res.json()).toEqual({ error: "Too many", code: "EXPORT_TOO_LARGE", details: { limit: 20000 } }); }); });