import { describe, test, expect } from "vitest"; import { readUploadResponse } from "./upload-client"; function jsonResponse(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" }, }); } function htmlResponse(status: number): Response { return new Response("Gateway Time-out", { status, headers: { "content-type": "text/html; charset=utf-8" }, }); } describe("readUploadResponse", () => { test("returns the path of a successful upload", async () => { const result = await readUploadResponse(jsonResponse({ path: "/uploads/abc.mp4" })); expect(result).toEqual({ ok: true, path: "/uploads/abc.mp4" }); }); test("passes through the server's own error message", async () => { const result = await readUploadResponse(jsonResponse({ error: "Die Datei ist zu groß (max. 100 MB)." }, 413)); expect(result).toEqual({ ok: false, kind: "message", message: "Die Datei ist zu groß (max. 100 MB)." }); }); test("reports an HTML error page by status instead of trying to parse it as JSON", async () => { // Der eigentliche Bug: response.json() auf einer HTML-Fehlerseite wirft // "Unexpected token '<', " { const result = await readUploadResponse(htmlResponse(413)); expect(result).toEqual({ ok: false, kind: "status", status: 413 }); }); test("treats a 200 response that is not JSON as a status failure", async () => { const result = await readUploadResponse(htmlResponse(200)); expect(result).toEqual({ ok: false, kind: "status", status: 200 }); }); test("treats JSON that is not parseable as a status failure", async () => { const broken = new Response("{ truncated", { status: 200, headers: { "content-type": "application/json" } }); expect(await readUploadResponse(broken)).toEqual({ ok: false, kind: "status", status: 200 }); }); test("treats a JSON success body without a path as a status failure", async () => { expect(await readUploadResponse(jsonResponse({}))).toEqual({ ok: false, kind: "status", status: 200 }); }); test("treats an empty body with an error status as a status failure", async () => { const empty = new Response(null, { status: 502 }); expect(await readUploadResponse(empty)).toEqual({ ok: false, kind: "status", status: 502 }); }); test("accepts a JSON content type that carries extra parameters", async () => { const res = new Response(JSON.stringify({ path: "/uploads/x.jpg" }), { status: 200, headers: { "content-type": "application/json; charset=utf-8" }, }); expect(await readUploadResponse(res)).toEqual({ ok: true, path: "/uploads/x.jpg" }); }); });