import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { getConnectivity, reportRequestOutcome } from "@/lib/offline/connectivity"; import { DEFAULT_TIMEOUT_MS, DOWNLOAD_TIMEOUT_MS, NON_IDEMPOTENT_WRITE_TIMEOUT_MS, UPLOAD_TIMEOUT_MS, } from "@/lib/http/fetch-with-timeout"; import { expectTimeoutAt, stubHangingFetch } from "@/lib/http/deadline-test-helper"; import { getAccessToken, setAccessToken, setRefreshedTokenHandler } from "./token-store"; import { ApiError, apiFetch, apiFetchBlob, apiFetchFormData } from "./api-client"; vi.mock("../config/runtime-config", () => ({ getApiUrl: vi.fn().mockResolvedValue("http://api.test"), })); function jsonResponse(status: number, body: unknown): Response { return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" }, }); } describe("api-client", () => { beforeEach(() => { setAccessToken(null); reportRequestOutcome("reached-server"); }); afterEach(() => { vi.unstubAllGlobals(); }); it("ApiError carries the parsed JSON body", async () => { vi.stubGlobal( "fetch", vi.fn().mockResolvedValue(jsonResponse(400, { message: "Ungültig", invalidColonyIds: ["c1"] })), ); const error = await apiFetch("/x").catch((e: unknown) => e); expect(error).toBeInstanceOf(ApiError); const apiError = error as ApiError; expect(apiError.status).toBe(400); expect(apiError.message).toBe("Ungültig"); expect((apiError.body as { invalidColonyIds: string[] }).invalidColonyIds).toEqual(["c1"]); }); describe("empty success bodies", () => { it.each([200, 201, 202])("resolves undefined for a %i with an empty body", async (status) => { vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("", { status }))); await expect(apiFetch("/x", { method: "POST" })).resolves.toBeUndefined(); }); it("resolves undefined for a 204", async () => { vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, { status: 204 }))); await expect(apiFetch("/x", { method: "POST" })).resolves.toBeUndefined(); }); it("resolves undefined when Content-Length is 0", async () => { vi.stubGlobal( "fetch", vi.fn().mockResolvedValue(new Response("", { status: 201, headers: { "Content-Length": "0" } })), ); await expect(apiFetch("/x", { method: "POST" })).resolves.toBeUndefined(); }); it("still parses a JSON body and still rejects invalid JSON", async () => { vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(201, { id: "a" }))); await expect(apiFetch("/x", { method: "POST" })).resolves.toEqual({ id: "a" }); vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("", { status: 200 }))); await expect(apiFetch("/x")).rejects.toBeInstanceOf(SyntaxError); }); }); it("reports network-error on a failed fetch and reached-server on any HTTP answer", async () => { vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("Failed to fetch"))); await expect(apiFetch("/x")).rejects.toBeInstanceOf(TypeError); expect(getConnectivity()).toBe("offline"); vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(500, { message: "boom" }))); await expect(apiFetch("/x")).rejects.toBeInstanceOf(ApiError); expect(getConnectivity()).toBe("online"); }); describe("timeouts", () => { beforeEach(() => { vi.useFakeTimers(); stubHangingFetch(); }); afterEach(() => { vi.useRealTimers(); }); it("apiFetch: GET and keyed writes 4 s, unkeyed writes 15 s", async () => { await expectTimeoutAt(() => apiFetch("/x"), DEFAULT_TIMEOUT_MS); await expectTimeoutAt( () => apiFetch("/x", { method: "POST", headers: { "Idempotency-Key": "k" } }), DEFAULT_TIMEOUT_MS, ); await expectTimeoutAt(() => apiFetch("/x", { method: "POST" }), NON_IDEMPOTENT_WRITE_TIMEOUT_MS); }); it("apiFetchFormData uses 30 s by default and honours timeoutMs", async () => { await expectTimeoutAt(() => apiFetchFormData("/x", new FormData()), UPLOAD_TIMEOUT_MS); await expectTimeoutAt( () => apiFetchFormData("/x", new FormData(), { timeoutMs: 5_000 }), 5_000, ); }); it("apiFetchFormData passes options.headers through", async () => { const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, {})); vi.stubGlobal("fetch", fetchMock); await apiFetchFormData("/x", new FormData(), { headers: { "Idempotency-Key": "k9" } }); const init = fetchMock.mock.calls[0][1] as RequestInit; expect(new Headers(init.headers).get("Idempotency-Key")).toBe("k9"); }); it("apiFetchBlob uses 60 s", async () => { await expectTimeoutAt(() => apiFetchBlob("/x", "f.csv"), DOWNLOAD_TIMEOUT_MS); }); }); it("apiFetchBlob passes the request options on, e.g. cache: no-store", async () => { const fetchMock = vi.fn().mockResolvedValue(new Response("pdf")); vi.stubGlobal("fetch", fetchMock); await apiFetchBlob("/x", "f.pdf", { cache: "no-store" }); expect((fetchMock.mock.calls[0][1] as RequestInit).cache).toBe("no-store"); }); it("apiFetchBlob builds an ApiError with the parsed body", async () => { vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(403, { message: "Nein", why: 1 }))); const error = (await apiFetchBlob("/x", "f.csv").catch((e: unknown) => e)) as ApiError; expect(error).toBeInstanceOf(ApiError); expect(error.status).toBe(403); expect(error.body).toEqual({ message: "Nein", why: 1 }); }); }); describe("api-client token refresh", () => { beforeEach(() => { setAccessToken(null); reportRequestOutcome("reached-server"); }); afterEach(() => { setRefreshedTokenHandler(null); vi.unstubAllGlobals(); }); function stubServer(refreshBody: unknown) { const fetchMock = vi.fn(async (url: string) => { if (url.endsWith("/auth/refresh")) return jsonResponse(200, refreshBody); const retried = fetchMock.mock.calls.filter(([called]) => called === url).length > 1; return retried ? jsonResponse(200, { ok: true }) : jsonResponse(401, {}); }); vi.stubGlobal("fetch", fetchMock); return fetchMock; } it("retries with the new token once the handler accepts it", async () => { const handler = vi.fn().mockResolvedValue(true); setRefreshedTokenHandler(handler); stubServer({ accessToken: "fresh" }); await expect(apiFetch("/things")).resolves.toEqual({ ok: true }); expect(handler).toHaveBeenCalledWith("fresh"); }); it("does not retry - and keeps no token - when the handler rejects it (another account)", async () => { setRefreshedTokenHandler(vi.fn().mockResolvedValue(false)); const fetchMock = stubServer({ accessToken: "other-users-token" }); await expect(apiFetch("/things")).rejects.toMatchObject({ status: 401 }); expect(getAccessToken()).toBeNull(); expect(fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/things"))).toHaveLength(1); }); it.each([ ["JSON", () => apiFetch("/proof", { method: "POST" }, { refreshOn401: false })], [ "form data", () => apiFetchFormData("/proof", new FormData(), { refreshOn401: false }), ], ])("sends %s once and shows the server's message on 401 with refreshOn401: false", async (_name, call) => { const fetchMock = vi.fn<(url: string) => Promise>(async () => jsonResponse(401, { message: "Das Passwort ist falsch." }), ); vi.stubGlobal("fetch", fetchMock); await expect(call()).rejects.toMatchObject({ status: 401, message: "Das Passwort ist falsch.", }); expect(fetchMock).toHaveBeenCalledTimes(1); expect(String(fetchMock.mock.calls[0]?.[0])).not.toContain("/auth/refresh"); }); it("takes the token as it is without a handler", async () => { stubServer({ accessToken: "fresh" }); await expect(apiFetch("/things")).resolves.toEqual({ ok: true }); expect(getAccessToken()).toBe("fresh"); }); it.each([ ["blobs", () => apiFetchBlob("/export", "x.csv")], ["form data", () => apiFetchFormData("/upload", new FormData())], ])("also asks the handler before retrying %s", async (_name, call) => { const handler = vi.fn().mockResolvedValue(false); setRefreshedTokenHandler(handler); stubServer({ accessToken: "other" }); await expect(call()).rejects.toBeInstanceOf(ApiError); expect(handler).toHaveBeenCalledWith("other"); expect(getAccessToken()).toBeNull(); }); });