Files
co-lite/solvway-admin-portal/app/interests/page.test.tsx
T
ngqileandClaude Opus 5.5 18672ba173 feat(admin-portal): interests screen
Lists, adds, renames, orders and activates/deactivates interests,
gated by BO_INTERESTS. API errors map to field messages under Name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-27 12:18:21 +08:00

261 lines
12 KiB
TypeScript

import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({
listAdminInterests: vi.fn(),
apiGet: vi.fn(),
apiPost: vi.fn(),
apiPut: vi.fn(),
useAdminAuth: vi.fn(),
}));
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
apiGet: mocks.apiGet,
apiPost: mocks.apiPost,
apiPut: mocks.apiPut,
}));
vi.mock("@/app/lib/services/adminInterests", async (importOriginal) => {
const mod = await importOriginal<typeof import("@/app/lib/services/adminInterests")>();
return { ...mod, listAdminInterests: mocks.listAdminInterests };
});
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
import InterestsPage from "./page";
import { ApiError } from "@/app/lib/clientApi";
beforeEach(() => {
mocks.listAdminInterests.mockReset();
mocks.apiGet.mockReset();
mocks.apiPost.mockReset();
mocks.apiPut.mockReset();
mocks.useAdminAuth.mockReset();
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true });
});
describe("InterestsPage", () => {
it("renders an empty table with no interests", async () => {
mocks.listAdminInterests.mockResolvedValue([]);
render(<InterestsPage />);
await waitFor(() => expect(screen.getByRole("table")).toBeInTheDocument());
expect(screen.getByText(/no interests/i)).toBeInTheDocument();
});
it("renders rows with name, order, and status badge", async () => {
mocks.listAdminInterests.mockResolvedValue([
{ id: 1, name: "Workshop", active: true, sortOrder: 1 },
{ id: 2, name: "Webinar", active: false, sortOrder: 2 },
]);
render(<InterestsPage />);
await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument());
const row1 = screen.getByText("Workshop").closest("tr")!;
expect(within(row1).getByText("1")).toBeInTheDocument();
expect(within(row1).getByText("Active")).toBeInTheDocument();
const row2 = screen.getByText("Webinar").closest("tr")!;
expect(within(row2).getByText("2")).toBeInTheDocument();
expect(within(row2).getByText("Inactive")).toBeInTheDocument();
});
it("posts trimmed name on create", async () => {
mocks.listAdminInterests.mockResolvedValue([]);
mocks.apiPost.mockResolvedValue({ id: 1, name: "New Interest", active: true, sortOrder: 0 });
render(<InterestsPage />);
await waitFor(() => expect(screen.getByText(/Add interest/i)).toBeInTheDocument());
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
expect(screen.getByRole("dialog")).toBeInTheDocument();
await userEvent.type(screen.getByLabelText(/Name/i), " New Interest ");
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
await waitFor(() =>
expect(mocks.apiPost).toHaveBeenCalledWith("/api/interests", {
name: "New Interest",
active: true,
sortOrder: 0,
}),
);
});
it("blocks submit when name is empty", async () => {
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Existing", active: true, sortOrder: 1 }]);
render(<InterestsPage />);
await waitFor(() => expect(screen.getByText("Existing")).toBeInTheDocument());
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
expect(screen.getByText(/Name is required/i)).toBeInTheDocument();
expect(mocks.apiPost).not.toHaveBeenCalled();
});
it("shows an unexpected save error at form level", async () => {
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Existing", active: true, sortOrder: 1 }]);
mocks.apiPost.mockRejectedValue(new Error("An interest with this name already exists."));
render(<InterestsPage />);
await waitFor(() => expect(screen.getByText("Existing")).toBeInTheDocument());
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
await userEvent.type(screen.getByLabelText(/Name/i), "Existing");
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
expect(await screen.findByText(/An interest with this name already exists/i)).toBeInTheDocument();
expect(screen.getByRole("dialog")).toBeInTheDocument();
});
it("deactivates interest via PUT { active: false }", async () => {
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Workshop", active: true, sortOrder: 1 }]);
mocks.apiPut.mockResolvedValue({ id: 1, name: "Workshop", active: false, sortOrder: 1 });
render(<InterestsPage />);
await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument());
const row = screen.getByText("Workshop").closest("tr")!;
await userEvent.click(within(row).getByRole("button", { name: /Deactivate/i }));
await waitFor(() =>
expect(mocks.apiPut).toHaveBeenCalledWith("/api/interests/1", expect.objectContaining({ active: false })),
);
});
it("activates interest via PUT { active: true }", async () => {
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Workshop", active: false, sortOrder: 1 }]);
mocks.apiPut.mockResolvedValue({ id: 1, name: "Workshop", active: true, sortOrder: 1 });
render(<InterestsPage />);
await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument());
const row = screen.getByText("Workshop").closest("tr")!;
await userEvent.click(within(row).getByRole("button", { name: /Activate/i }));
await waitFor(() =>
expect(mocks.apiPut).toHaveBeenCalledWith("/api/interests/1", expect.objectContaining({ active: true })),
);
});
it("edit dialog: name field, order number input, PUTs on save", async () => {
mocks.listAdminInterests.mockResolvedValue([
{ id: 1, name: "Workshop", active: true, sortOrder: 5 },
]);
mocks.apiPut.mockResolvedValue({ id: 1, name: "Workshop Edited", active: true, sortOrder: 10 });
render(<InterestsPage />);
await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument());
const row = screen.getByText("Workshop").closest("tr")!;
await userEvent.click(within(row).getByRole("button", { name: /Edit/i }));
expect(screen.getByRole("dialog")).toBeInTheDocument();
expect(screen.getByLabelText(/Name/i)).toHaveValue("Workshop");
expect(screen.getByLabelText(/Order/i)).toHaveValue(5);
await userEvent.clear(screen.getByLabelText(/Name/i));
await userEvent.type(screen.getByLabelText(/Name/i), "Workshop Edited");
await userEvent.clear(screen.getByLabelText(/Order/i));
await userEvent.type(screen.getByLabelText(/Order/i), "10");
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
await waitFor(() =>
expect(mocks.apiPut).toHaveBeenCalledWith("/api/interests/1", {
id: 1,
name: "Workshop Edited",
sortOrder: 10,
}),
);
});
it("shows NotAuthorized when the module is missing", async () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
render(<InterestsPage />);
await waitFor(() => expect(screen.getByRole("alert")).toBeInTheDocument());
expect(screen.getByText(/not authorised/i)).toBeInTheDocument();
});
it("shows IntDuplicateName under Name when API returns DUPLICATE_NAME error", async () => {
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Existing", active: true, sortOrder: 1 }]);
const dupErr = new ApiError("Conflict", 409, { code: "DUPLICATE_NAME", details: { field: "name" } });
mocks.apiPost.mockRejectedValue(dupErr);
render(<InterestsPage />);
await waitFor(() => expect(screen.getByText("Existing")).toBeInTheDocument());
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
await userEvent.type(screen.getByLabelText(/Name/i), "Existing");
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
// The field error for DUPLICATE_NAME should appear under the Name input
const nameInput = screen.getByLabelText(/Name/i);
const nameField = nameInput.closest(".space-y-1\\.5")!;
await waitFor(() => {
expect(nameField.querySelector('[role="alert"]')?.textContent).toContain("An interest with this name already exists.");
});
});
it("shows IntNameTooLong under Name when API returns TOO_LONG error", async () => {
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Existing", active: true, sortOrder: 1 }]);
const tooLongErr = new ApiError("Name is too long.", 422, { code: "TOO_LONG", details: { field: "name" } });
mocks.apiPost.mockRejectedValue(tooLongErr);
render(<InterestsPage />);
await waitFor(() => expect(screen.getByText("Existing")).toBeInTheDocument());
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
await userEvent.type(screen.getByLabelText(/Name/i), "A name that is way too long to be valid for an interest");
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
const nameInput = screen.getByLabelText(/Name/i);
const nameField = nameInput.closest(".space-y-1\\.5")!;
await waitFor(() => {
expect(nameField.querySelector('[role="alert"]')?.textContent).toContain("Name must be 100 characters or fewer.");
});
});
it("submits successfully with a 100-character name", async () => {
// maxLength={100} on the input prevents typing 101+ chars.
// The handleSubmit guard (trimmed.length > 100) is defense-in-depth.
// We verify the boundary works by submitting exactly 100 characters.
mocks.listAdminInterests.mockResolvedValue([]);
render(<InterestsPage />);
await waitFor(() => expect(screen.getByText(/Add interest/i)).toBeInTheDocument());
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
await userEvent.type(screen.getByLabelText(/Name/i), "A".repeat(100));
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
await waitFor(() =>
expect(mocks.apiPost).toHaveBeenCalledWith("/api/interests", expect.objectContaining({ name: "A".repeat(100) })),
);
});
it("shows activate/deactivate failure error on the page", async () => {
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Workshop", active: true, sortOrder: 1 }]);
mocks.apiPut.mockRejectedValue(new ApiError("Network error", 0));
render(<InterestsPage />);
await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument());
const row = screen.getByText("Workshop").closest("tr")!;
await userEvent.click(within(row).getByRole("button", { name: /Deactivate/i }));
expect(await screen.findByText("Failed to deactivate interest.")).toBeInTheDocument();
});
it("shows activate failure on the page", async () => {
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Workshop", active: false, sortOrder: 1 }]);
mocks.apiPut.mockRejectedValue(new ApiError("Network error", 0));
render(<InterestsPage />);
await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument());
const row = screen.getByText("Workshop").closest("tr")!;
await userEvent.click(within(row).getByRole("button", { name: /^Activate$/i }));
expect(await screen.findByText("Failed to activate interest.")).toBeInTheDocument();
});
it("blocks a name over 100 characters before submit", async () => {
mocks.listAdminInterests.mockResolvedValue([]);
render(<InterestsPage />);
await waitFor(() => expect(screen.getByText(/Add interest/i)).toBeInTheDocument());
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
fireEvent.change(screen.getByLabelText(/Name/i), { target: { value: "A".repeat(101) } });
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
expect(await screen.findByText("Name must be 100 characters or fewer.")).toBeInTheDocument();
expect(mocks.apiPost).not.toHaveBeenCalled();
});
});