Files
co-lite/solvway-admin-portal/app/components/pages/PageEditor.test.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

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

310 lines
13 KiB
TypeScript

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 { CmsPageView } from "@/app/lib/cmsPages";
// add-cms-pages Task 8: the page editor (specs/admin-portal-cms-pages-ui "The Page Editor Builds A
// Page From Blocks").
const router = vi.hoisted(() => ({ replace: vi.fn(), push: vi.fn(), search: new URLSearchParams() }));
vi.mock("next/navigation", () => ({ useRouter: () => router, useSearchParams: () => router.search }));
const pages = vi.hoisted(() => ({
getPage: vi.fn(),
savePage: vi.fn(),
deletePage: vi.fn(),
uploadPageImage: vi.fn(),
listPages: vi.fn(),
}));
vi.mock("@/app/lib/services/adminPages", () => pages);
const collections = vi.hoisted(() => ({ listCollections: vi.fn() }));
vi.mock("@/app/lib/services/adminCollections", () => collections);
// Tiptap does not run in jsdom; the editor is a labelled textarea here.
vi.mock("@/app/components/products/RichTextEditor", () => ({
RichTextEditor: ({ id, value, onChange }: { id?: string; value: string; onChange: (v: string) => void }) => (
<textarea id={id} value={value} onChange={(e) => onChange(e.target.value)} />
),
}));
import { ApiError } from "@/app/lib/clientApi";
import { StorefrontOriginProvider } from "@/app/lib/storefront";
import { PageEditor } from "./PageEditor";
const saved: CmsPageView = {
id: 9,
slug: "about-us",
title: "About us",
metaDescription: null,
status: "Y",
blocks: [],
updatedAt: "2026-10-06T10:00:00",
};
beforeEach(() => {
Object.values(pages).forEach((f) => f.mockReset());
collections.listCollections.mockReset();
router.replace.mockReset();
router.push.mockReset();
router.search = new URLSearchParams();
collections.listCollections.mockResolvedValue([
{ id: 7, slug: "gift-sets", title: "Gift sets", type: "MANUAL", status: "Y", productCount: 3, updatedAt: null },
{ id: 8, slug: "newborn", title: "Newborn", type: "AUTOMATIC", status: "Y", productCount: 9, updatedAt: null },
]);
pages.savePage.mockResolvedValue(saved);
});
const block = (n: number) => screen.getByRole("group", { name: new RegExp(`^Block ${n}:`) });
async function addBlock(label: string) {
await userEvent.click(screen.getByRole("button", { name: `Add ${label}` }));
}
describe("PageEditor — page fields", () => {
it("fills the slug from the title until the slug is edited", async () => {
render(<PageEditor />);
await userEvent.type(screen.getByLabelText(/^Title/), "About Us");
expect(screen.getByLabelText(/^Slug/)).toHaveValue("about-us");
await userEvent.clear(screen.getByLabelText(/^Slug/));
await userEvent.type(screen.getByLabelText(/^Slug/), "our-story");
await userEvent.type(screen.getByLabelText(/^Title/), " page");
expect(screen.getByLabelText(/^Slug/)).toHaveValue("our-story");
});
it("counts the meta description against 160 characters", async () => {
render(<PageEditor />);
await userEvent.type(screen.getByLabelText(/^Meta description/), "Hello there!");
expect(screen.getByText("12/160")).toBeInTheDocument();
});
it("offers Visible and Hidden, Visible by default", () => {
render(<PageEditor />);
expect(screen.getByRole("radio", { name: "Visible" })).toBeChecked();
expect(screen.getByRole("radio", { name: "Hidden" })).not.toBeChecked();
});
});
describe("PageEditor — blocks", () => {
it("adds each block type with its own fields", async () => {
render(<PageEditor />);
await addBlock("Hero");
expect(within(block(1)).getByLabelText("Block image")).toBeInTheDocument();
expect(within(block(1)).getByLabelText(/^Heading/)).toBeInTheDocument();
expect(within(block(1)).getByLabelText(/^Button label/)).toBeInTheDocument();
expect(within(block(1)).getByLabelText(/^Button link/)).toBeInTheDocument();
await addBlock("Rich text");
expect(within(block(2)).getByLabelText(/^Content/)).toBeInTheDocument();
await addBlock("Image with text");
expect(within(block(3)).getByRole("radio", { name: "Image on the left" })).toBeChecked();
expect(within(block(3)).getByRole("radio", { name: "Image on the right" })).toBeInTheDocument();
await addBlock("Featured products");
expect(within(block(4)).getByLabelText(/^Collection/)).toBeInTheDocument();
expect(within(block(4)).getByLabelText(/^Number of products/)).toHaveValue(8);
await addBlock("Collection list");
expect(within(block(5)).getByLabelText(/^Add collection/)).toBeInTheDocument();
await addBlock("FAQ");
expect(within(block(6)).getByLabelText("Question 1")).toBeInTheDocument();
expect(within(block(6)).getByLabelText("Answer 1")).toBeInTheDocument();
await userEvent.click(within(block(6)).getByRole("button", { name: "Add question" }));
expect(within(block(6)).getByLabelText("Question 2")).toBeInTheDocument();
});
it("moves and removes blocks", async () => {
render(<PageEditor />);
await addBlock("Hero");
await addBlock("Rich text");
await addBlock("FAQ");
await userEvent.click(within(block(3)).getByRole("button", { name: "Move up" }));
expect(block(2)).toHaveAccessibleName(/FAQ/);
expect(block(3)).toHaveAccessibleName(/Rich text/);
await userEvent.click(within(block(1)).getByRole("button", { name: "Move down" }));
expect(block(1)).toHaveAccessibleName(/FAQ/);
expect(block(2)).toHaveAccessibleName(/Hero/);
await userEvent.click(within(block(2)).getByRole("button", { name: "Remove" }));
expect(screen.getAllByRole("group", { name: /^Block \d:/ })).toHaveLength(2);
expect(screen.queryByRole("group", { name: /Hero/ })).not.toBeInTheDocument();
});
it("builds a collection list in picked order", async () => {
render(<PageEditor />);
await addBlock("Collection list");
await userEvent.selectOptions(within(block(1)).getByLabelText(/^Add collection/), "8");
await userEvent.selectOptions(within(block(1)).getByLabelText(/^Add collection/), "7");
expect(within(block(1)).getAllByRole("listitem").map((li) => li.textContent)).toEqual([
expect.stringContaining("Newborn"),
expect.stringContaining("Gift sets"),
]);
});
});
describe("PageEditor — saving", () => {
it("saves the page fields and blocks in order", async () => {
render(<PageEditor />);
await userEvent.type(screen.getByLabelText(/^Title/), "About us");
await userEvent.type(screen.getByLabelText(/^Meta description/), "Who we are");
await userEvent.click(screen.getByRole("radio", { name: "Hidden" }));
await addBlock("Rich text");
await userEvent.type(within(block(1)).getByLabelText(/^Content/), "<p>Hi</p>");
await addBlock("Featured products");
await userEvent.selectOptions(within(block(2)).getByLabelText(/^Collection/), "7");
await addBlock("FAQ");
await userEvent.type(within(block(3)).getByLabelText("Question 1"), "Shipping?");
await userEvent.type(within(block(3)).getByLabelText("Answer 1"), "Free over RM100.");
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
await waitFor(() => expect(pages.savePage).toHaveBeenCalledTimes(1));
expect(pages.savePage.mock.calls[0][0]).toEqual({
title: "About us",
slug: "about-us",
metaDescription: "Who we are",
status: "N",
blocks: [
{ type: "RICH_TEXT", html: "<p>Hi</p>" },
{ type: "FEATURED_PRODUCTS", collectionId: 7, limit: 8 },
{ type: "FAQ", items: [{ question: "Shipping?", answer: "Free over RM100." }] },
],
});
await waitFor(() => expect(router.replace).toHaveBeenCalledWith("/pages/9?saved=1"));
});
it("uploads a chosen block image only on save, then saves with its URL", async () => {
pages.uploadPageImage.mockResolvedValue({ url: "https://cdn/cms-page/hero.png" });
render(<PageEditor />);
await userEvent.type(screen.getByLabelText(/^Title/), "Sale");
await addBlock("Hero");
await userEvent.upload(within(block(1)).getByLabelText("Block image"), new File(["png"], "hero.png", { type: "image/png" }));
await userEvent.type(within(block(1)).getByLabelText(/^Heading/), "Big sale");
expect(pages.uploadPageImage).not.toHaveBeenCalled();
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
await waitFor(() => expect(pages.savePage).toHaveBeenCalledTimes(1));
expect(pages.uploadPageImage).toHaveBeenCalledTimes(1);
expect(pages.uploadPageImage.mock.calls[0][0]).toMatchObject({ fileName: "hero.png", fileType: "image/png" });
expect(pages.uploadPageImage.mock.calls[0][0].base).toBeTruthy();
expect(pages.savePage.mock.calls[0][0].blocks[0]).toEqual({ type: "HERO", imageUrl: "https://cdn/cms-page/hero.png", heading: "Big sale" });
});
it("does not upload the image again when retrying after a failed save", async () => {
pages.uploadPageImage.mockResolvedValue({ url: "https://cdn/cms-page/hero.png" });
pages.savePage.mockRejectedValueOnce(new ApiError("Server down", 500)).mockResolvedValue(saved);
render(<PageEditor />);
await userEvent.type(screen.getByLabelText(/^Title/), "Sale");
await addBlock("Hero");
await userEvent.upload(within(block(1)).getByLabelText("Block image"), new File(["png"], "hero.png", { type: "image/png" }));
await userEvent.type(within(block(1)).getByLabelText(/^Heading/), "Big sale");
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
expect(await screen.findByText("Server down")).toBeInTheDocument();
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
await waitFor(() => expect(pages.savePage).toHaveBeenCalledTimes(2));
expect(pages.uploadPageImage).toHaveBeenCalledTimes(1);
expect(pages.savePage.mock.calls[1][0].blocks[0].imageUrl).toBe("https://cdn/cms-page/hero.png");
});
it("shows a server field error on its block field and keeps every value", async () => {
pages.savePage.mockRejectedValue(new ApiError("blocks[0].buttonUrl: must start with / or https://", 422));
render(<PageEditor />);
await userEvent.type(screen.getByLabelText(/^Title/), "Sale");
await addBlock("Rich text");
await userEvent.type(within(block(1)).getByLabelText(/^Content/), "<p>x</p>");
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
expect(await within(block(1)).findByText("must start with / or https://")).toBeInTheDocument();
expect(screen.getByLabelText(/^Title/)).toHaveValue("Sale");
expect(within(block(1)).getByLabelText(/^Content/)).toHaveValue("<p>x</p>");
});
it("shows a page-level field error next to its field", async () => {
pages.savePage.mockRejectedValue(new ApiError("slug: another page already uses about-us", 422));
render(<PageEditor />);
await userEvent.type(screen.getByLabelText(/^Title/), "About us");
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
expect(await screen.findByText("another page already uses about-us")).toBeInTheDocument();
});
});
describe("PageEditor — existing page", () => {
it("loads a page, keeps its slug fixed to the title, and confirms the save", async () => {
pages.getPage.mockResolvedValue({
...saved,
blocks: [{ type: "FAQ", heading: "Questions", items: [{ question: "Q?", answer: "A." }] }],
});
render(<PageEditor pageId={9} />);
expect(await screen.findByDisplayValue("About us")).toBeInTheDocument();
expect(pages.getPage).toHaveBeenCalledWith(9);
expect(within(block(1)).getByLabelText("Question 1")).toHaveValue("Q?");
await userEvent.type(screen.getByLabelText(/^Title/), "!");
expect(screen.getByLabelText(/^Slug/)).toHaveValue("about-us");
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
expect(await screen.findByText("Page saved")).toBeInTheDocument();
expect(pages.savePage.mock.calls[0][0]).toMatchObject({ id: 9 });
expect(router.replace).not.toHaveBeenCalled();
});
it("links to the storefront page of a saved visible page", async () => {
pages.getPage.mockResolvedValue({ ...saved, slug: "contact" });
render(<PageEditor pageId={9} />);
expect(await screen.findByRole("link", { name: /view page/i })).toHaveAttribute("href", expect.stringMatching(/\/contact$/));
});
it("links the view-page button to the runtime portal origin", async () => {
pages.getPage.mockResolvedValue({ ...saved, slug: "contact" });
render(
<StorefrontOriginProvider origin="https://user.babyboo.my">
<PageEditor pageId={9} />
</StorefrontOriginProvider>,
);
expect(await screen.findByRole("link", { name: /view page/i })).toHaveAttribute(
"href",
expect.stringMatching(/^https:\/\/user\.babyboo\.my\/.*contact$/),
);
});
it("deletes only after confirmation", async () => {
pages.getPage.mockResolvedValue(saved);
pages.deletePage.mockResolvedValue({ ok: true });
render(<PageEditor pageId={9} />);
await screen.findByDisplayValue("About us");
await userEvent.click(screen.getByRole("button", { name: "Delete page" }));
expect(pages.deletePage).not.toHaveBeenCalled();
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" }));
await waitFor(() => expect(pages.deletePage).toHaveBeenCalledWith(9));
expect(router.push).toHaveBeenCalledWith("/pages");
});
it("shows the saved notice after a new page's redirect", async () => {
router.search = new URLSearchParams("saved=1");
pages.getPage.mockResolvedValue(saved);
render(<PageEditor pageId={9} />);
expect(await screen.findByText("Page saved")).toBeInTheDocument();
});
});