280 lines
9.3 KiB
TypeScript
280 lines
9.3 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { Mock } from "vitest";
|
|
import type { Session } from "next-auth";
|
|
|
|
// Mirrors tests/employees.test.ts's @/auth mocking pattern.
|
|
vi.mock("@/auth", () => ({ auth: vi.fn() }));
|
|
|
|
import { GET, POST } from "@/app/api/assets/route";
|
|
import { prisma } from "@/lib/prisma";
|
|
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/assets", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify(body),
|
|
});
|
|
}
|
|
|
|
// AssetItem.purchaseOrderId is a real FK to PurchaseOrder (see
|
|
// schema.prisma / src/lib/assets.ts), and PurchaseOrder.vendorId is a real
|
|
// FK to Vendor — tests that need a valid purchaseOrderId create real rows
|
|
// first and use their ids. Mirrors tests/purchase-orders.test.ts's
|
|
// createTestVendor() helper.
|
|
function createTestVendor(overrides: { name?: string } = {}) {
|
|
return prisma.vendor.create({
|
|
data: {
|
|
name: overrides.name ?? "Test Vendor",
|
|
contactEmail: "[email protected]",
|
|
contactPhone: "0281234567",
|
|
address: "123 Test Street",
|
|
},
|
|
});
|
|
}
|
|
|
|
function createTestPurchaseOrder(overrides: { vendorId?: string } = {}) {
|
|
return prisma.purchaseOrder.create({
|
|
data: {
|
|
vendorId: overrides.vendorId as string,
|
|
orderDate: new Date("2026-08-01"),
|
|
expectedDate: new Date("2026-08-10"),
|
|
},
|
|
});
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
// Each test starts from empty tables so listing/order assertions are
|
|
// deterministic. asset_items must be cleared before purchase_orders/
|
|
// vendors since asset_items has FKs (ON DELETE SET NULL to
|
|
// purchase_orders) — deleteMany order avoids relying on that cascade
|
|
// behavior in tests. purchase_orders must be cleared before vendors
|
|
// (ON DELETE RESTRICT to vendors, mirrors tests/purchase-orders.test.ts).
|
|
await prisma.assetItem.deleteMany();
|
|
await prisma.purchaseOrder.deleteMany();
|
|
await prisma.vendor.deleteMany();
|
|
// Default to a logged-in session — the tests below exercise business
|
|
// logic, not auth gating (that's covered by the "auth gating" describe
|
|
// block further down).
|
|
mockedAuth.mockResolvedValue(testSession);
|
|
});
|
|
|
|
describe("POST /api/assets", () => {
|
|
it("creates an asset item in in_stock status on valid input, with no warrantyEndDate", async () => {
|
|
const res = await POST(
|
|
postRequest({ serialNumber: "SN-001", model: "Dell Latitude 5440", purchaseDate: "2026-01-15" })
|
|
);
|
|
|
|
expect(res.status).toBe(201);
|
|
const body = await res.json();
|
|
|
|
expect(body).toMatchObject({
|
|
serial_number: "SN-001",
|
|
model: "Dell Latitude 5440",
|
|
status: "in_stock",
|
|
warranty_end_date: null,
|
|
});
|
|
expect(typeof body.id).toBe("string");
|
|
expect(body.id.length).toBeGreaterThan(0);
|
|
expect(Number.isNaN(Date.parse(body.purchase_date))).toBe(false);
|
|
expect(Number.isNaN(Date.parse(body.created_at))).toBe(false);
|
|
});
|
|
|
|
it("creates an asset item with a warrantyEndDate", async () => {
|
|
const res = await POST(
|
|
postRequest({
|
|
serialNumber: "SN-002",
|
|
model: "Dell Latitude 5440",
|
|
purchaseDate: "2026-01-15",
|
|
warrantyEndDate: "2029-01-15",
|
|
})
|
|
);
|
|
|
|
expect(res.status).toBe(201);
|
|
const body = await res.json();
|
|
expect(Number.isNaN(Date.parse(body.warranty_end_date))).toBe(false);
|
|
});
|
|
|
|
it("rejects an empty serialNumber", async () => {
|
|
const res = await POST(postRequest({ serialNumber: "", model: "Dell", purchaseDate: "2026-01-15" }));
|
|
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json();
|
|
expect(body.error).toMatch(/serialNumber/i);
|
|
});
|
|
|
|
it("rejects an empty model", async () => {
|
|
const res = await POST(postRequest({ serialNumber: "SN-003", model: "", purchaseDate: "2026-01-15" }));
|
|
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json();
|
|
expect(body.error).toMatch(/model/i);
|
|
});
|
|
|
|
it("rejects an invalid purchaseDate", async () => {
|
|
const res = await POST(
|
|
postRequest({ serialNumber: "SN-004", model: "Dell", purchaseDate: "not-a-date" })
|
|
);
|
|
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json();
|
|
expect(body.error).toMatch(/purchaseDate/i);
|
|
});
|
|
|
|
it("rejects an invalid warrantyEndDate", async () => {
|
|
const res = await POST(
|
|
postRequest({
|
|
serialNumber: "SN-005",
|
|
model: "Dell",
|
|
purchaseDate: "2026-01-15",
|
|
warrantyEndDate: "not-a-date",
|
|
})
|
|
);
|
|
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json();
|
|
expect(body.error).toMatch(/warrantyEndDate/i);
|
|
});
|
|
|
|
it("creates an asset item with a purchaseOrderId that references a real purchase order", async () => {
|
|
const vendor = await createTestVendor();
|
|
const purchaseOrder = await createTestPurchaseOrder({ vendorId: vendor.id });
|
|
|
|
const res = await POST(
|
|
postRequest({
|
|
serialNumber: "SN-007",
|
|
model: "Dell Latitude 5440",
|
|
purchaseDate: "2026-01-15",
|
|
purchaseOrderId: purchaseOrder.id,
|
|
})
|
|
);
|
|
|
|
expect(res.status).toBe(201);
|
|
const body = await res.json();
|
|
expect(body.purchase_order_id).toBe(purchaseOrder.id);
|
|
});
|
|
|
|
it("creates an asset item with no purchaseOrderId (stays null)", async () => {
|
|
const res = await POST(
|
|
postRequest({ serialNumber: "SN-008", model: "Dell Latitude 5440", purchaseDate: "2026-01-15" })
|
|
);
|
|
|
|
expect(res.status).toBe(201);
|
|
const body = await res.json();
|
|
expect(body.purchase_order_id).toBeNull();
|
|
});
|
|
|
|
it("rejects a purchaseOrderId that is a well-formed UUID but doesn't reference an existing purchase order", async () => {
|
|
const res = await POST(
|
|
postRequest({
|
|
serialNumber: "SN-009",
|
|
model: "Dell Latitude 5440",
|
|
purchaseDate: "2026-01-15",
|
|
purchaseOrderId: "00000000-0000-0000-0000-000000000000",
|
|
})
|
|
);
|
|
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json();
|
|
expect(body.error).toMatch(/purchaseOrderId/i);
|
|
expect(body.error).toMatch(/does not reference an existing purchase order/i);
|
|
|
|
// And it must not have created anything.
|
|
const remaining = await prisma.assetItem.findMany();
|
|
expect(remaining).toHaveLength(0);
|
|
});
|
|
|
|
it("rejects a purchaseOrderId that is not a valid UUID", async () => {
|
|
const res = await POST(
|
|
postRequest({
|
|
serialNumber: "SN-012",
|
|
model: "Dell Latitude 5440",
|
|
purchaseDate: "2026-01-15",
|
|
purchaseOrderId: "not-a-uuid",
|
|
})
|
|
);
|
|
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json();
|
|
expect(body.error).toMatch(/purchaseOrderId/i);
|
|
});
|
|
|
|
it("rejects a duplicate serialNumber", async () => {
|
|
await POST(postRequest({ serialNumber: "SN-006", model: "Dell", purchaseDate: "2026-01-15" }));
|
|
const res = await POST(postRequest({ serialNumber: "SN-006", model: "HP", purchaseDate: "2026-02-01" }));
|
|
|
|
expect(res.status).toBe(400);
|
|
const body = await res.json();
|
|
expect(body.error).toMatch(/serialNumber already exists/i);
|
|
|
|
// And it must not have created a second row.
|
|
const remaining = await prisma.assetItem.findMany();
|
|
expect(remaining).toHaveLength(1);
|
|
});
|
|
});
|
|
|
|
describe("GET /api/assets", () => {
|
|
it("lists created asset items, newest first", async () => {
|
|
await POST(postRequest({ serialNumber: "SN-010", model: "Dell", purchaseDate: "2026-01-15" }));
|
|
// Ensure a distinct created_at ordering even on fast filesystems/clocks.
|
|
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
await POST(postRequest({ serialNumber: "SN-011", model: "HP", purchaseDate: "2026-02-01" }));
|
|
|
|
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({ serial_number: "SN-011", model: "HP" });
|
|
expect(body[1]).toMatchObject({ serial_number: "SN-010", model: "Dell" });
|
|
});
|
|
|
|
it("returns an empty list when there are no asset items", async () => {
|
|
const res = await GET();
|
|
expect(res.status).toBe(200);
|
|
const body = await res.json();
|
|
expect(body).toEqual([]);
|
|
});
|
|
});
|
|
|
|
describe("auth gating on /api/assets", () => {
|
|
// Mirrors tests/employees.test.ts's "auth gating" block — only checks
|
|
// session presence, per the flat permission model (no role/permission
|
|
// logic).
|
|
it("POST /api/assets returns 401 without a session", async () => {
|
|
mockedAuth.mockResolvedValue(null);
|
|
|
|
const res = await POST(
|
|
postRequest({ serialNumber: "SN-020", model: "Dell", purchaseDate: "2026-01-15" })
|
|
);
|
|
|
|
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.assetItem.findMany();
|
|
expect(remaining).toHaveLength(0);
|
|
});
|
|
|
|
it("GET /api/assets 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" });
|
|
});
|
|
});
|