Files
famapp/tests/unit/api-v1-calendar.test.ts

67 lines
2.4 KiB
TypeScript

import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { z } from "zod";
import { apiError, apiJson, mapApiError, withApiHandler } from "../../src/lib/api-handler";
describe("apiJson", () => {
it("returns JSON with default 200 status", async () => {
const response = apiJson({ ok: true });
assert.equal(response.status, 200);
assert.equal(response.headers.get("Content-Type"), "application/json");
assert.deepEqual(await response.json(), { ok: true });
});
it("accepts custom status codes", async () => {
const response = apiJson({ created: true }, 201);
assert.equal(response.status, 201);
});
});
describe("apiError", () => {
it("returns error payload with given status", async () => {
const response = apiError("Unauthorized", 401);
assert.equal(response.status, 401);
assert.deepEqual(await response.json(), { error: "Unauthorized" });
});
});
describe("mapApiError", () => {
it("maps Zod validation errors to 400", async () => {
const err = z.object({ name: z.string().min(1) }).safeParse({}).error;
assert.ok(err);
const response = mapApiError(err);
assert.equal(response.status, 400);
});
it("maps not-found errors to 404", async () => {
const response = mapApiError(new Error("Calendar not found"));
assert.equal(response.status, 404);
assert.deepEqual(await response.json(), { error: "Calendar not found" });
});
it("maps forbidden errors to 403", async () => {
const response = mapApiError(new Error("Forbidden"));
assert.equal(response.status, 403);
assert.deepEqual(await response.json(), { error: "Forbidden" });
});
});
describe("withApiHandler", () => {
it("returns 401 when requireApiAuth throws a Response", async () => {
const request = new Request("http://localhost/api/v1/calendars");
const response = await withApiHandler(request, async () => apiJson([]));
assert.equal(response.status, 401);
assert.deepEqual(await response.json(), { error: "Unauthorized" });
});
});
describe("GET /api/v1/calendars auth gate", () => {
it("returns 401 without authentication", async () => {
const { GET } = await import("../../src/app/api/v1/calendars/route");
const request = new Request("http://localhost/api/v1/calendars");
const response = await GET(request);
assert.equal(response.status, 401);
assert.deepEqual(await response.json(), { error: "Unauthorized" });
});
});