test: add AssetCategory API tests

This commit is contained in:
toanhoang
2026-08-02 20:32:38 -04:00
parent 63eb3df33d
commit aaab8fd9b7
+306
View File
@@ -0,0 +1,306 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Mock } from "vitest";
import type { Session } from "next-auth";
import {
createAssetCategory,
listAssetCategories,
validateCreateAssetCategoryInput,
} from "@/lib/asset-categories";
import { prisma } from "@/lib/prisma";
// Note: this file has two layers of coverage, mirroring tests/vendors.test.ts:
// - lib-level tests below exercise src/lib/asset-categories.ts directly
// (validation, valueGroup enum, list ordering).
// - route-level tests (further down) exercise
// src/app/api/asset-categories/route.ts over HTTP, including the auth()
// gate — mirrors tests/vendors.test.ts's @/auth mocking pattern.
vi.mock("@/auth", () => ({ auth: vi.fn() }));
import { GET, POST } from "@/app/api/asset-categories/route";
import { auth } from "@/auth";
const mockedAuth = auth as unknown as Mock<() => Promise<Session | null>>;
const testSession: Session = {
user: { id: "test-user-id" },
expires: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
};
function postRequest(body: unknown): Request {
return new Request("http://localhost/api/asset-categories", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
beforeEach(async () => {
// Each test starts from an empty table so listing/order assertions are
// deterministic.
await prisma.assetCategory.deleteMany();
// Default to a logged-in session — the lib-level tests below don't go
// through the route at all (so this is a no-op for them), and the
// route-level tests exercise business logic, not auth gating (that's
// covered by the "auth gating" describe block further down).
mockedAuth.mockResolvedValue(testSession);
});
describe("validateCreateAssetCategoryInput", () => {
it("accepts a valid high_value category", () => {
const result = validateCreateAssetCategoryInput({
name: "Laptop",
valueGroup: "high_value",
});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value).toMatchObject({ name: "Laptop", valueGroup: "high_value" });
}
});
it("accepts a valid low_value category", () => {
const result = validateCreateAssetCategoryInput({
name: "Cáp HDMI",
valueGroup: "low_value",
});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value).toMatchObject({ name: "Cáp HDMI", valueGroup: "low_value" });
}
});
it("rejects an empty name", () => {
const result = validateCreateAssetCategoryInput({
name: "",
valueGroup: "high_value",
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toMatch(/name/i);
}
});
it("rejects a missing name", () => {
const result = validateCreateAssetCategoryInput({
valueGroup: "high_value",
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toMatch(/name/i);
}
});
it("rejects an invalid valueGroup", () => {
const result = validateCreateAssetCategoryInput({
name: "Laptop",
valueGroup: "medium_value",
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toMatch(/valueGroup/i);
}
});
it("rejects a missing valueGroup", () => {
const result = validateCreateAssetCategoryInput({
name: "Laptop",
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toMatch(/valueGroup/i);
}
});
});
describe("createAssetCategory", () => {
it("creates a high_value category", async () => {
const result = validateCreateAssetCategoryInput({
name: "Laptop",
valueGroup: "high_value",
});
expect(result.ok).toBe(true);
if (!result.ok) return;
const created = await createAssetCategory(result.value);
expect(created.ok).toBe(true);
if (!created.ok) return;
expect(created.value).toMatchObject({ name: "Laptop", value_group: "high_value" });
expect(typeof created.value.id).toBe("string");
expect(created.value.id.length).toBeGreaterThan(0);
expect(Number.isNaN(Date.parse(created.value.created_at))).toBe(false);
});
it("creates a low_value category", async () => {
const result = validateCreateAssetCategoryInput({
name: "Cáp HDMI",
valueGroup: "low_value",
});
expect(result.ok).toBe(true);
if (!result.ok) return;
const created = await createAssetCategory(result.value);
expect(created.ok).toBe(true);
if (!created.ok) return;
expect(created.value).toMatchObject({ name: "Cáp HDMI", value_group: "low_value" });
});
});
describe("listAssetCategories", () => {
it("lists created categories, newest first", async () => {
const first = validateCreateAssetCategoryInput({ name: "Cáp HDMI", valueGroup: "low_value" });
expect(first.ok).toBe(true);
if (first.ok) await createAssetCategory(first.value);
// Ensure a distinct created_at ordering even on fast filesystems/clocks.
await new Promise((resolve) => setTimeout(resolve, 5));
const second = validateCreateAssetCategoryInput({ name: "Laptop", valueGroup: "high_value" });
expect(second.ok).toBe(true);
if (second.ok) await createAssetCategory(second.value);
const records = await listAssetCategories();
expect(records).toHaveLength(2);
// newest first
expect(records[0]).toMatchObject({ name: "Laptop" });
expect(records[1]).toMatchObject({ name: "Cáp HDMI" });
});
it("returns an empty list when there are no categories", async () => {
const records = await listAssetCategories();
expect(records).toEqual([]);
});
});
describe("POST /api/asset-categories", () => {
it("creates a high_value category on valid input", async () => {
const res = await POST(postRequest({ name: "Laptop", valueGroup: "high_value" }));
expect(res.status).toBe(201);
const body = await res.json();
expect(body).toMatchObject({ name: "Laptop", value_group: "high_value" });
expect(typeof body.id).toBe("string");
expect(body.id.length).toBeGreaterThan(0);
expect(Number.isNaN(Date.parse(body.created_at))).toBe(false);
});
it("creates a low_value category on valid input", async () => {
const res = await POST(postRequest({ name: "Cáp HDMI", valueGroup: "low_value" }));
expect(res.status).toBe(201);
const body = await res.json();
expect(body).toMatchObject({ name: "Cáp HDMI", value_group: "low_value" });
});
it("rejects an empty name", async () => {
const res = await POST(postRequest({ name: "", valueGroup: "high_value" }));
expect(res.status).toBe(400);
const body = await res.json();
expect(body.error).toMatch(/name/i);
});
it("rejects an invalid valueGroup", async () => {
const res = await POST(postRequest({ name: "Laptop", valueGroup: "medium_value" }));
expect(res.status).toBe(400);
const body = await res.json();
expect(body.error).toMatch(/valueGroup/i);
});
it("rejects a missing valueGroup", async () => {
const res = await POST(postRequest({ name: "Laptop" }));
expect(res.status).toBe(400);
const body = await res.json();
expect(body.error).toMatch(/valueGroup/i);
});
it("rejects an invalid JSON body", async () => {
const req = new Request("http://localhost/api/asset-categories", {
method: "POST",
headers: { "content-type": "application/json" },
body: "not json",
});
const res = await POST(req);
expect(res.status).toBe(400);
const body = await res.json();
expect(body.error).toMatch(/JSON/i);
});
it("rejects a non-object JSON body", async () => {
// Note: arrays are `typeof "object"` in JS, so they pass the route's
// object check (same behavior as /api/vendors) — use a JSON string
// primitive here to actually exercise the "not an object" branch.
const res = await POST(postRequest("not an object"));
expect(res.status).toBe(400);
const body = await res.json();
expect(body.error).toMatch(/JSON object/i);
});
});
describe("GET /api/asset-categories", () => {
it("lists created categories, newest first", async () => {
await POST(postRequest({ name: "Cáp HDMI", valueGroup: "low_value" }));
// Ensure a distinct created_at ordering even on fast filesystems/clocks.
await new Promise((resolve) => setTimeout(resolve, 5));
await POST(postRequest({ name: "Laptop", valueGroup: "high_value" }));
const res = await GET();
expect(res.status).toBe(200);
const body = await res.json();
expect(Array.isArray(body)).toBe(true);
expect(body).toHaveLength(2);
// newest first
expect(body[0]).toMatchObject({ name: "Laptop" });
expect(body[1]).toMatchObject({ name: "Cáp HDMI" });
});
it("returns an empty list when there are no categories", async () => {
const res = await GET();
expect(res.status).toBe(200);
const body = await res.json();
expect(body).toEqual([]);
});
});
describe("auth gating on /api/asset-categories", () => {
// Mirrors tests/vendors.test.ts's "auth gating" block — only checks
// session presence, per the flat permission model (no role/permission
// logic).
it("POST /api/asset-categories returns 401 without a session", async () => {
mockedAuth.mockResolvedValue(null);
const res = await POST(postRequest({ name: "Laptop", valueGroup: "high_value" }));
expect(res.status).toBe(401);
const body = await res.json();
expect(body).toEqual({ error: "Unauthorized" });
// And it must not have created anything.
const remaining = await prisma.assetCategory.findMany();
expect(remaining).toHaveLength(0);
});
it("GET /api/asset-categories returns 401 without a session", async () => {
mockedAuth.mockResolvedValue(null);
const res = await GET();
expect(res.status).toBe(401);
const body = await res.json();
expect(body).toEqual({ error: "Unauthorized" });
});
});