// @vitest-environment jsdom import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { apiGet, apiPost, apiPut, apiDelete, apiDownload, ApiError } from "./clientApi"; function jsonResponse(body: unknown, status: number): Response { return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" }, }); } describe("clientApi", () => { const originalFetch = global.fetch; const originalAssign = window.location.assign; beforeEach(() => { global.fetch = vi.fn(); // jsdom's window.location.assign is unimplemented navigation; stub it so the // 401 redirect path is observable instead of throwing "Not implemented". Object.defineProperty(window, "location", { value: { ...window.location, assign: vi.fn() }, writable: true, }); }); afterEach(() => { global.fetch = originalFetch; Object.defineProperty(window, "location", { value: { ...window.location, assign: originalAssign }, writable: true }); }); it("apiGet resolves the parsed JSON body on success", async () => { (global.fetch as ReturnType).mockResolvedValue(jsonResponse({ name: "Admin" }, 200)); await expect(apiGet<{ name: string }>("/api/auth/session")).resolves.toEqual({ name: "Admin" }); }); it("apiPost sends a JSON body and Content-Type header", async () => { (global.fetch as ReturnType).mockResolvedValue(jsonResponse({ ok: true }, 200)); await apiPost("/api/auth/login", { username: "a", password: "b" }); expect(global.fetch).toHaveBeenCalledWith( "/api/auth/login", expect.objectContaining({ method: "POST", body: JSON.stringify({ username: "a", password: "b" }), headers: expect.objectContaining({ "Content-Type": "application/json" }), }), ); }); it("apiPut passes caller-provided headers alongside Content-Type", async () => { (global.fetch as ReturnType).mockResolvedValue(jsonResponse({ ok: true }, 200)); await apiPut("/api/roles/4/modules", { moduleIds: [40800000] }, { "X-Trace-Id": "abc" }); expect(global.fetch).toHaveBeenCalledWith( "/api/roles/4/modules", expect.objectContaining({ method: "PUT", body: JSON.stringify({ moduleIds: [40800000] }), headers: expect.objectContaining({ "Content-Type": "application/json", "X-Trace-Id": "abc" }), }), ); }); it("apiDelete sends a DELETE with no body (module-tree delete)", async () => { (global.fetch as ReturnType).mockResolvedValue(new Response(null, { status: 204 })); await apiDelete("/api/modules/41800000"); expect(global.fetch).toHaveBeenCalledWith( "/api/modules/41800000", expect.objectContaining({ method: "DELETE", headers: expect.not.objectContaining({ "Content-Type": "application/json" }), }), ); }); it("throws ApiError with the server's message on failure", async () => { (global.fetch as ReturnType).mockResolvedValue( jsonResponse({ error: "Invalid username or password" }, 400), ); await expect(apiGet("/api/members")).rejects.toMatchObject({ message: "Invalid username or password", status: 400, }); }); // Ruling R3: an authenticated client call that gets a 401 (expired/absent // session, e.g. a cookie that decodes but whose token the mobile-api has // since rejected) must bounce the browser to /login, not just reject. it("redirects to /login on a 401 response", async () => { (global.fetch as ReturnType).mockResolvedValue(jsonResponse({ error: "Not authenticated" }, 401)); await expect(apiGet("/api/members")).rejects.toBeInstanceOf(ApiError); expect(window.location.assign).toHaveBeenCalledWith("/login"); }); it("redirects to /reset-password on 403 PASSWORD_RESET_REQUIRED", async () => { (global.fetch as ReturnType).mockResolvedValue( jsonResponse({ error: "PASSWORD_RESET_REQUIRED", code: "PASSWORD_RESET_REQUIRED" }, 403), ); await expect(apiGet("/api/members")).rejects.toBeInstanceOf(ApiError); expect(window.location.assign).toHaveBeenCalledWith("/reset-password"); }); it("does not redirect on other 403s", async () => { (global.fetch as ReturnType).mockResolvedValue(jsonResponse({ error: "Forbidden" }, 403)); await expect(apiGet("/api/members")).rejects.toBeInstanceOf(ApiError); expect(window.location.assign).not.toHaveBeenCalled(); }); it("a 401 from the login call shows its message instead of redirecting", async () => { (global.fetch as ReturnType).mockResolvedValue( jsonResponse({ error: "This account is disabled. Contact your administrator." }, 401), ); await expect(apiPost("/api/auth/login", { username: "u", password: "p" })).rejects.toMatchObject({ message: "This account is disabled. Contact your administrator.", status: 401, }); expect(window.location.assign).not.toHaveBeenCalled(); }); // unify-admin-listing-toolbar: a request that never reaches the server (offline, connection reset) // used to surface the browser's raw "Failed to fetch". it("throws a readable ApiError with status 0 when the request cannot reach the server", async () => { (global.fetch as ReturnType).mockRejectedValue(new TypeError("Failed to fetch")); const err = await apiGet("/api/admin/event-summary/7").catch((e: unknown) => e); expect(err).toBeInstanceOf(ApiError); expect((err as ApiError).message).toBe("Couldn't reach the server. Check your connection and retry."); expect((err as ApiError).status).toBe(0); expect(window.location.assign).not.toHaveBeenCalled(); }); it("does not swallow an abort", async () => { const abort = new DOMException("The operation was aborted.", "AbortError"); (global.fetch as ReturnType).mockRejectedValue(abort); await expect(apiGet("/api/x")).rejects.toBe(abort); }); }); describe("apiDownload", () => { const originalFetch = global.fetch; afterEach(() => { global.fetch = originalFetch; vi.restoreAllMocks(); }); function stubUrl() { const create = vi.fn(() => "blob:x"); const revoke = vi.fn(); Object.assign(URL, { createObjectURL: create, revokeObjectURL: revoke }); const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {}); return { create, revoke, click }; } it("downloads using the filename from Content-Disposition and revokes the URL", async () => { const { create, revoke, click } = stubUrl(); global.fetch = vi.fn().mockResolvedValue(new Response("bytes", { status: 200, headers: { "Content-Disposition": 'attachment; filename="leads-2026.xlsx"' } })); let name = ""; click.mockImplementation(function (this: HTMLAnchorElement) { name = this.download; }); await apiDownload("/api/leads/export?q=a", "leads.xlsx"); expect(global.fetch).toHaveBeenCalledWith("/api/leads/export?q=a", expect.anything()); expect(create).toHaveBeenCalled(); expect(name).toBe("leads-2026.xlsx"); await vi.waitFor(() => expect(revoke).toHaveBeenCalledWith("blob:x")); }); it("falls back to the given filename", async () => { const { click } = stubUrl(); global.fetch = vi.fn().mockResolvedValue(new Response("bytes", { status: 200 })); let name = ""; click.mockImplementation(function (this: HTMLAnchorElement) { name = this.download; }); await apiDownload("/api/leads/export", "leads.xlsx"); expect(name).toBe("leads.xlsx"); }); it("throws an ApiError carrying code and details on failure", async () => { stubUrl(); global.fetch = vi.fn().mockResolvedValue(jsonResponse({ error: "Too many", code: "EXPORT_TOO_LARGE", details: { limit: 20000 } }, 422)); await expect(apiDownload("/api/leads/export", "leads.xlsx")).rejects.toMatchObject({ name: "ApiError", status: 422, message: "Too many", data: { code: "EXPORT_TOO_LARGE", details: { limit: 20000 } }, }); }); });