Something went wrong. Try again.
Tea journaling on ATProto (alpha) forked from arabica.social/arabica
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199import { describe, expect, it, vi } from "vitest";import { ApiError, apiGet, apiRequest, apiSend } from "../../lib/api";
interface FetchCall { url: URL; init: RequestInit;}
function stubFetch( handler: (url: URL, init: RequestInit) => Response | Promise<Response>,): FetchCall[] { const calls: FetchCall[] = []; vi.stubGlobal( "fetch", vi.fn(async (input: RequestInfo | URL, init: RequestInit = {}) => { const url = new URL(String(input), "http://localhost"); calls.push({ url, init }); return handler(url, init); }), ); return calls;}
function jsonResponse(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" }, });}
function fakeLocation(pathname: string) { const original = window.location; const assign = vi.fn(); Object.defineProperty(window, "location", { configurable: true, value: { pathname, search: "", origin: "http://localhost", assign }, }); return { assign, restore: () => Object.defineProperty(window, "location", { configurable: true, value: original, }), };}
describe("api client", () => { it("asks for JSON with same-origin credentials and returns the parsed body", async () => { const calls = stubFetch(() => jsonResponse({ items: [], cursor: "", has_more: false }), );
const page = await apiGet<{ items: unknown[]; has_more: boolean }>( "/api/feed?limit=20", );
expect(page).toEqual({ items: [], cursor: "", has_more: false }); const headers = new Headers(calls[0].init.headers); expect(headers.get("Accept")).toBe("application/json"); expect(headers.get("Content-Type")).toBeNull(); expect(calls[0].init.credentials).toBe("same-origin"); expect(calls[0].init.method).toBe("GET"); });
it("preserves browser-generated multipart boundaries", async () => { const calls = stubFetch(() => jsonResponse({ saved: true })); const body = new FormData(); body.set("display_name", "Alex"); await apiRequest("/api/settings/bluesky-profile", { method: "POST", body }); const headers = new Headers(calls[0].init.headers); expect(headers.get("Content-Type")).toBeNull(); expect(headers.get("Accept")).toBe("application/json"); expect(calls[0].init.body).toBe(body); });
it("sends mutations as JSON", async () => { const calls = stubFetch(() => jsonResponse({ rkey: "brew-1" }));
await apiSend("POST", "/api/brews", { tea_rkey: "tea-1", style: "longSteep", });
const headers = new Headers(calls[0].init.headers); expect(headers.get("Content-Type")).toBe("application/json"); expect(calls[0].init.method).toBe("POST"); expect(JSON.parse(String(calls[0].init.body))).toEqual({ tea_rkey: "tea-1", style: "longSteep", }); });
it("surfaces the server's error envelope as an ApiError", async () => { stubFetch(() => jsonResponse({ error: "Invalid steep", code: "validation_failed" }, 422), );
const failure = await apiGet("/api/brews/nope").catch( (error: unknown) => error, );
expect(failure).toBeInstanceOf(ApiError); expect(failure).toMatchObject({ status: 422, code: "validation_failed", message: "Invalid steep", }); });
it("falls back to http_<status> for plain-text failures", async () => { stubFetch( () => new Response("upstream exploded", { status: 500, headers: { "content-type": "text/plain" }, }), );
const failure = (await apiGet("/api/feed").catch( (error: unknown) => error, )) as ApiError;
expect(failure).toBeInstanceOf(ApiError); expect(failure.status).toBe(500); expect(failure.code).toBe("http_500"); expect(failure.message).toBe("upstream exploded"); });
it("reports an unreachable server as a network error", async () => { stubFetch(() => Promise.reject(new TypeError("Failed to fetch")));
const failure = (await apiGet("/api/feed").catch( (error: unknown) => error, )) as ApiError;
expect(failure).toBeInstanceOf(ApiError); expect(failure.status).toBe(0); expect(failure.code).toBe("network_error"); expect(failure.message).toContain("Could not reach Oolong"); });
it("redirects an expired session to login with the current path", async () => { stubFetch(() => jsonResponse( { error: "Authentication required", code: "authentication_required" }, 401, ), ); const location = fakeLocation("/brews/new"); try { const failure = (await apiGet("/api/data").catch( (error: unknown) => error, )) as ApiError; expect(failure.status).toBe(401); expect(location.assign).toHaveBeenCalledWith( "/login?return=%2Fbrews%2Fnew", ); } finally { location.restore(); } });
it("leaves the redirect to the caller when suppressed", async () => { stubFetch(() => jsonResponse( { error: "Authentication required", code: "authentication_required" }, 401, ), ); const location = fakeLocation("/brews/new"); try { const failure = (await apiGet("/api/session", { suppressAuthRedirect: true, }).catch((error: unknown) => error)) as ApiError; expect(failure.status).toBe(401); expect(location.assign).not.toHaveBeenCalled(); } finally { location.restore(); } });
it("forwards the abort signal and rethrows the abort", async () => { const controller = new AbortController(); const calls = stubFetch((_url, init) => { expect(init.signal).toBe(controller.signal); return Promise.reject(new DOMException("Aborted", "AbortError")); });
const failure = await apiGet("/api/feed", { signal: controller.signal, }).catch((error: unknown) => error);
expect(failure).toBeInstanceOf(DOMException); expect((failure as DOMException).name).toBe("AbortError"); expect(calls).toHaveLength(1); });});