import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { CmsFormView } from "@/app/lib/cmsForms";
// add-cms-forms Task 9: the form editor (specs/admin-portal-cms-forms-ui "The Form Editor Builds A
// Form From Fields", "Deleting A Form Asks First").
const router = vi.hoisted(() => ({ replace: vi.fn(), push: vi.fn(), search: new URLSearchParams() }));
vi.mock("next/navigation", () => ({ useRouter: () => router, useSearchParams: () => router.search }));
const forms = vi.hoisted(() => ({
getForm: vi.fn(),
saveForm: vi.fn(),
deleteForm: vi.fn(),
listForms: vi.fn(),
listSubmissions: vi.fn(),
getSubmission: vi.fn(),
deleteSubmission: vi.fn(),
}));
vi.mock("@/app/lib/services/adminForms", () => forms);
import { ApiError } from "@/app/lib/clientApi";
import { FormEditor } from "./FormEditor";
const stored: CmsFormView = {
id: 3,
name: "Contact us",
submitLabel: "Send",
successMessage: "Thanks!",
notifyEmails: ["team@babyboo.my"],
status: "Y",
fields: [
{ key: "name", label: "Name", type: "TEXT", required: true },
{ key: "topic", label: "Topic", type: "SELECT", required: false, options: ["Order", "Billing"] },
],
updatedAt: "2026-10-07T10:00:00",
};
beforeEach(() => {
Object.values(forms).forEach((f) => f.mockReset());
router.replace.mockReset();
router.push.mockReset();
router.search = new URLSearchParams();
forms.saveForm.mockResolvedValue(stored);
forms.getForm.mockResolvedValue(stored);
});
const field = (n: number) => screen.getByRole("group", { name: `Field ${n}` });
describe("FormEditor", () => {
it("saves a new form with the exact body and opens it", async () => {
render();
await userEvent.type(screen.getByLabelText("Name"), "Contact us");
await userEvent.type(screen.getByLabelText(/^Notification emails/), "a@babyboo.my, b@babyboo.my");
await userEvent.click(screen.getByRole("button", { name: "Add field" }));
await userEvent.type(within(field(2)).getByLabelText("Label"), "Email");
await userEvent.selectOptions(within(field(2)).getByLabelText("Type"), "EMAIL");
await userEvent.click(within(field(2)).getByLabelText("Required"));
await userEvent.click(screen.getByRole("button", { name: "Save form" }));
await waitFor(() => expect(forms.saveForm).toHaveBeenCalledTimes(1));
const body = forms.saveForm.mock.calls[0][0];
expect(body).toMatchObject({
name: "Contact us",
submitLabel: "Send",
successMessage: "Thanks! We'll be in touch soon.",
notifyEmails: ["a@babyboo.my", "b@babyboo.my"],
status: "Y",
});
expect(body.id).toBeUndefined();
expect(body.fields).toHaveLength(2);
expect(body.fields[0]).toMatchObject({ label: "Name", type: "TEXT", required: true });
expect(body.fields[1]).toMatchObject({ label: "Email", type: "EMAIL", required: true });
expect(body.fields[1].options).toBeUndefined();
expect(body.fields[0].key).not.toBe(body.fields[1].key);
expect(router.replace).toHaveBeenCalledWith("/forms/3?saved=1");
});
it("loads a form and keeps field keys when saving it again", async () => {
render();
expect(await screen.findByDisplayValue("Contact us")).toBeInTheDocument();
expect(screen.getByLabelText(/^Notification emails/)).toHaveValue("team@babyboo.my");
expect(within(field(2)).getByLabelText(/^Options/)).toHaveValue("Order\nBilling");
await userEvent.click(screen.getByRole("button", { name: "Save form" }));
await waitFor(() => expect(forms.saveForm).toHaveBeenCalledTimes(1));
expect(forms.saveForm.mock.calls[0][0]).toEqual({
id: 3,
name: "Contact us",
submitLabel: "Send",
successMessage: "Thanks!",
notifyEmails: ["team@babyboo.my"],
status: "Y",
fields: stored.fields,
});
expect(router.replace).not.toHaveBeenCalled();
expect(await screen.findByRole("status")).toHaveTextContent("Form saved");
});
it("adds, moves and removes fields", async () => {
render();
await userEvent.click(screen.getByRole("button", { name: "Add field" }));
await userEvent.type(within(field(2)).getByLabelText("Label"), "Phone");
await userEvent.click(within(field(2)).getByRole("button", { name: "Move field up" }));
expect(within(field(1)).getByLabelText("Label")).toHaveValue("Phone");
expect(within(field(2)).getByLabelText("Label")).toHaveValue("Name");
await userEvent.click(within(field(1)).getByRole("button", { name: "Remove field" }));
expect(screen.getAllByRole("group", { name: /^Field \d+$/ })).toHaveLength(1);
expect(within(field(1)).getByLabelText("Label")).toHaveValue("Name");
});
it("shows options only for a dropdown", async () => {
render();
expect(within(field(1)).queryByLabelText(/^Options/)).not.toBeInTheDocument();
await userEvent.selectOptions(within(field(1)).getByLabelText("Type"), "SELECT");
expect(within(field(1)).getByLabelText(/^Options/)).toBeInTheDocument();
expect(within(field(1)).getByRole("option", { name: "Dropdown" })).toBeInTheDocument();
});
it("shows a server rejection under the field it names and keeps the input", async () => {
forms.saveForm.mockRejectedValue(new ApiError("fields[1].options: must have 1 to 30 options", 422));
render();
await userEvent.type(screen.getByLabelText("Name"), "Contact us");
await userEvent.click(screen.getByRole("button", { name: "Add field" }));
await userEvent.type(within(field(2)).getByLabelText("Label"), "Topic");
await userEvent.selectOptions(within(field(2)).getByLabelText("Type"), "SELECT");
await userEvent.click(screen.getByRole("button", { name: "Save form" }));
const message = await within(field(2)).findByText("must have 1 to 30 options");
expect(message.closest("[data-field='options']")).not.toBeNull();
expect(within(field(1)).queryByRole("alert")).not.toBeInTheDocument();
expect(within(field(2)).getByLabelText("Label")).toHaveValue("Topic");
expect(screen.getByLabelText("Name")).toHaveValue("Contact us");
});
it("shows a bad notification address under the emails field", async () => {
forms.saveForm.mockRejectedValue(new ApiError("notifyEmails[1]: must be a valid email address", 422));
render();
await userEvent.click(screen.getByRole("button", { name: "Save form" }));
const message = await screen.findByText("must be a valid email address");
expect(message.closest("[data-field='notifyEmails']")).not.toBeNull();
});
it("deletes only after confirmation", async () => {
forms.deleteForm.mockResolvedValue({ ok: true });
render();
await screen.findByDisplayValue("Contact us");
await userEvent.click(screen.getByRole("button", { name: "Delete form" }));
expect(forms.deleteForm).not.toHaveBeenCalled();
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" }));
await waitFor(() => expect(forms.deleteForm).toHaveBeenCalledWith(3));
expect(router.push).toHaveBeenCalledWith("/forms");
});
it("shows the refusal when the form has submissions", async () => {
forms.deleteForm.mockRejectedValue(
new ApiError("This form has submissions. Hide it instead, or delete its submissions first.", 409),
);
render();
await screen.findByDisplayValue("Contact us");
await userEvent.click(screen.getByRole("button", { name: "Delete form" }));
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" }));
expect(await screen.findByText("This form has submissions. Hide it instead, or delete its submissions first.")).toBeInTheDocument();
expect(router.push).not.toHaveBeenCalled();
});
// Task 9 review: a rejection the editor has no slot for is still shown.
it("shows a rejection for a path it does not render in the summary alert", async () => {
forms.saveForm.mockRejectedValue(new ApiError("fields[1]: must not be null", 422));
render();
await userEvent.click(screen.getByRole("button", { name: "Save form" }));
expect(await screen.findByText("fields[1]: must not be null")).toBeInTheDocument();
});
// Task 9 review: errors are by position, so moving or removing a field clears them.
it("clears field errors when fields move or are removed", async () => {
forms.saveForm.mockRejectedValue(new ApiError("fields[1].label: is required, at most 120 characters", 422));
render();
await userEvent.click(screen.getByRole("button", { name: "Add field" }));
await userEvent.click(screen.getByRole("button", { name: "Save form" }));
expect(await within(field(2)).findByText("is required, at most 120 characters")).toBeInTheDocument();
await userEvent.click(within(field(2)).getByRole("button", { name: "Move field up" }));
expect(screen.queryByText("is required, at most 120 characters")).not.toBeInTheDocument();
});
});