Files
co-lite/solvway-admin-portal/app/components/users/UserForm.test.tsx
T
ngqileandClaude Opus 5.5 da813874ec feat(admin-portal): forgot password page; own account cannot be deactivated
/forgot-password always shows the same message; the route never forwards upstream
errors or a token. /api/admin/me now returns id and username so the user form can
lock the Active switch on your own account.

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

249 lines
9.2 KiB
TypeScript

import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({
listAdminRoles: vi.fn(),
useAdminAuth: vi.fn(),
}));
vi.mock("@/app/lib/services/adminRoles", () => ({ listAdminRoles: mocks.listAdminRoles }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
import { UserForm } from "./UserForm";
const ROLES = [
{ id: 1, name: "ROLE_IT", level: 1, parent: { id: 0 } },
{ id: 2, name: "ROLE_HQ", level: 1, parent: { id: 0 } },
];
beforeEach(() => {
mocks.listAdminRoles.mockReset().mockResolvedValue(ROLES);
mocks.useAdminAuth.mockReset().mockReturnValue({ id: null });
});
async function waitForPickers() {
await waitFor(() => expect(screen.getByLabelText("IT")).toBeInTheDocument());
}
describe("UserForm", () => {
it("renders all fields including the role picker", async () => {
render(<UserForm onSubmit={vi.fn()} />);
await waitForPickers();
expect(screen.getByLabelText("Name")).toBeInTheDocument();
expect(screen.getByLabelText("Surname")).toBeInTheDocument();
expect(screen.getByLabelText("Username")).toBeInTheDocument();
expect(screen.getByLabelText("Email")).toBeInTheDocument();
expect(screen.getByLabelText("IT")).toBeInTheDocument();
expect(screen.getByLabelText("HQ")).toBeInTheDocument();
expect(screen.queryByRole("combobox", { name: "User Group" })).not.toBeInTheDocument();
expect(screen.queryByRole("combobox", { name: "Branch" })).not.toBeInTheDocument();
expect(screen.queryByRole("combobox", { name: "Status" })).not.toBeInTheDocument();
expect(screen.getByLabelText("Enabled")).toBeInTheDocument();
expect(screen.getByText("Disabled users cannot sign in.")).toBeInTheDocument();
});
it("derives status from the Enabled switch on save", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(
<UserForm
initial={{
id: 9,
name: "Jane",
username: "jane.doe",
email: "jane@example.com",
enabled: true,
status: "P",
roles: [],
}}
onSubmit={onSubmit}
/>,
);
await waitForPickers();
await userEvent.click(screen.getByLabelText("Enabled"));
await userEvent.click(screen.getByRole("button", { name: /save/i }));
await waitFor(() =>
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ enabled: false, status: "N" })),
);
});
it("blocks submit and shows errors when required fields are missing", async () => {
const onSubmit = vi.fn();
render(<UserForm onSubmit={onSubmit} />);
await waitForPickers();
await userEvent.click(screen.getByRole("button", { name: /save/i }));
expect(await screen.findByText("Name is required.")).toBeInTheDocument();
expect(screen.getByText("Username is required.")).toBeInTheDocument();
expect(screen.getByText("Email is required.")).toBeInTheDocument();
expect(onSubmit).not.toHaveBeenCalled();
});
it("blocks submit on an invalid email", async () => {
const onSubmit = vi.fn();
render(<UserForm onSubmit={onSubmit} />);
await waitForPickers();
await userEvent.type(screen.getByLabelText("Name"), "Jane");
await userEvent.type(screen.getByLabelText("Username"), "jane.doe");
await userEvent.type(screen.getByLabelText("Email"), "not-an-email");
await userEvent.click(screen.getByRole("button", { name: /save/i }));
expect(await screen.findByText(/valid email/i)).toBeInTheDocument();
expect(onSubmit).not.toHaveBeenCalled();
});
it("builds the correct AdminUser payload on submit", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(<UserForm onSubmit={onSubmit} />);
await waitForPickers();
await userEvent.type(screen.getByLabelText("Name"), "Jane");
await userEvent.type(screen.getByLabelText("Surname"), "Doe");
await userEvent.type(screen.getByLabelText("Username"), "jane.doe");
await userEvent.type(screen.getByLabelText("Email"), "jane@example.com");
await userEvent.click(screen.getByLabelText("IT"));
await userEvent.click(screen.getByLabelText("HQ"));
await userEvent.click(screen.getByRole("button", { name: /save/i }));
await waitFor(() =>
expect(onSubmit).toHaveBeenCalledWith({
id: undefined,
name: "Jane",
surname: "Doe",
username: "jane.doe",
email: "jane@example.com",
enabled: true,
status: "Y",
roles: expect.arrayContaining([
{ id: 1, name: "ROLE_IT" },
{ id: 2, name: "ROLE_HQ" },
]),
}),
);
});
it("removing a selected role chip unchecks it", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(<UserForm onSubmit={onSubmit} />);
await waitForPickers();
await userEvent.click(screen.getByLabelText("IT"));
expect(screen.getByRole("checkbox", { name: "IT" })).toBeChecked();
await userEvent.click(screen.getByRole("button", { name: "Remove IT" }));
expect(screen.getByRole("checkbox", { name: "IT" })).not.toBeChecked();
});
it("prefills from an initial AdminUser (edit mode)", async () => {
render(
<UserForm
initial={{
id: 9,
name: "Jane",
surname: "Doe",
username: "jane.doe",
email: "jane@example.com",
enabled: false,
status: "N",
roles: [{ id: 1, name: "ROLE_IT" }],
}}
onSubmit={vi.fn()}
/>,
);
await waitForPickers();
expect(screen.getByLabelText("Name")).toHaveValue("Jane");
expect(screen.getByLabelText("Username")).toHaveValue("jane.doe");
expect(screen.getByLabelText("Email")).toHaveValue("jane@example.com");
expect(screen.getByRole("checkbox", { name: "IT" })).toBeChecked();
expect(screen.getByLabelText("Enabled")).not.toBeChecked();
});
it("disables submit while the save is pending", async () => {
let resolveSubmit!: () => void;
const onSubmit = vi.fn(
() =>
new Promise<void>((resolve) => {
resolveSubmit = resolve;
}),
);
render(<UserForm onSubmit={onSubmit} />);
await waitForPickers();
await userEvent.type(screen.getByLabelText("Name"), "Jane");
await userEvent.type(screen.getByLabelText("Username"), "jane.doe");
await userEvent.type(screen.getByLabelText("Email"), "jane@example.com");
await userEvent.click(screen.getByRole("button", { name: /save/i }));
await waitFor(() => expect(screen.getByRole("button", { name: /save/i })).toBeDisabled());
resolveSubmit();
});
it("shows an error and re-enables submit when onSubmit rejects", async () => {
const onSubmit = vi.fn().mockRejectedValue(new Error("Username already taken"));
render(<UserForm onSubmit={onSubmit} />);
await waitForPickers();
await userEvent.type(screen.getByLabelText("Name"), "Jane");
await userEvent.type(screen.getByLabelText("Username"), "jane.doe");
await userEvent.type(screen.getByLabelText("Email"), "jane@example.com");
await userEvent.click(screen.getByRole("button", { name: /save/i }));
expect(await screen.findByText(/username already taken/i)).toBeInTheDocument();
expect(screen.getByRole("button", { name: /save/i })).not.toBeDisabled();
});
it.each([
["USERNAME_TAKEN", "Username is already taken"],
["SELF_DEACTIVATION", "You cannot deactivate your own account"],
["EMAIL_TAKEN", "Email is already in use"],
])("shows the API's %s message on a failed save", async (_code, message) => {
render(
<UserForm
initial={{ id: 9, name: "Jane", username: "jane", email: "jane@example.com", enabled: true, status: "Y", roles: [] }}
onSubmit={vi.fn().mockRejectedValue(new Error(message))}
/>,
);
await waitForPickers();
await userEvent.click(screen.getByRole("button", { name: /save/i }));
expect(await screen.findByText(message)).toBeInTheDocument();
});
describe("own account", () => {
const record = { id: 9, name: "Jane", username: "jane", email: "jane@example.com", enabled: true, status: "Y" as const, roles: [] };
it("disables the Active switch and shows the hint when editing the signed-in user", async () => {
mocks.useAdminAuth.mockReturnValue({ id: 9 });
render(<UserForm initial={record} onSubmit={vi.fn()} />);
await waitForPickers();
expect(screen.getByLabelText("Enabled")).toBeDisabled();
expect(screen.getByText("You can't deactivate your own account")).toBeInTheDocument();
});
it("keeps the Active switch enabled when editing another user", async () => {
mocks.useAdminAuth.mockReturnValue({ id: 1 });
render(<UserForm initial={record} onSubmit={vi.fn()} />);
await waitForPickers();
expect(screen.getByLabelText("Enabled")).not.toBeDisabled();
expect(screen.queryByText("You can't deactivate your own account")).not.toBeInTheDocument();
});
it("keeps the switch enabled on the create form", async () => {
mocks.useAdminAuth.mockReturnValue({ id: 9 });
render(<UserForm onSubmit={vi.fn()} />);
await waitForPickers();
expect(screen.getByLabelText("Enabled")).not.toBeDisabled();
});
});
});