Files
co-lite/solvway-admin-portal/app/components/pages/PageEditor.blocks.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

235 lines
10 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, second lock (review of the first implementation): every block field the
// spec defines, images that follow their block, inline rich-text uploads, partial-upload retry.
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);
// The rich-text editor stand-in exposes its image upload hook as a button.
vi.mock("@/app/components/products/RichTextEditor", () => ({
RichTextEditor: ({ id, value, onChange, onUploadImage }: {
id?: string; value: string; onChange: (v: string) => void; onUploadImage?: (file: File) => Promise<string>;
}) => (
<>
<textarea id={id} value={value} onChange={(e) => onChange(e.target.value)} />
<button
type="button"
onClick={async () => {
const url = await onUploadImage?.(new File(["png"], "inline.png", { type: "image/png" }));
onChange(`${value}<img src="${url}">`);
}}
>
Insert image
</button>
</>
),
}));
import { ApiError } from "@/app/lib/clientApi";
import { PageEditor } from "./PageEditor";
const saved: CmsPageView = { id: 9, slug: "about-us", title: "About us", metaDescription: null, status: "Y", blocks: [], updatedAt: null };
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 },
]);
pages.savePage.mockResolvedValue(saved);
});
const block = (n: number) => screen.getByRole("group", { name: new RegExp(`^Block ${n}:`) });
const addBlock = (label: string) => userEvent.click(screen.getByRole("button", { name: `Add ${label}` }));
const png = (name: string) => new File(["png"], name, { type: "image/png" });
describe("every field the spec defines", () => {
it("hero has a text line; image with text has its own rich text", async () => {
render(<PageEditor />);
await userEvent.type(screen.getByLabelText(/^Title/), "Sale");
await addBlock("Hero");
await userEvent.type(within(block(1)).getByLabelText(/^Heading/), "Big sale");
await userEvent.type(within(block(1)).getByLabelText(/^Text/), "This week only");
await addBlock("Image with text");
await userEvent.type(within(block(2)).getByLabelText(/^Heading/), "Our story");
await userEvent.type(within(block(2)).getByLabelText(/^Text/), "<p>Since 2010</p>");
await userEvent.click(within(block(2)).getByRole("radio", { name: "Image on the right" }));
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
await waitFor(() => expect(pages.savePage).toHaveBeenCalledTimes(1));
expect(pages.savePage.mock.calls[0][0].blocks).toEqual([
{ type: "HERO", heading: "Big sale", text: "This week only" },
{ type: "IMAGE_TEXT", heading: "Our story", html: "<p>Since 2010</p>", imagePosition: "RIGHT" },
]);
});
it("featured products, collection list and FAQ each have an optional heading", async () => {
render(<PageEditor />);
await addBlock("Featured products");
await addBlock("Collection list");
await addBlock("FAQ");
for (const n of [1, 2, 3]) {
expect(within(block(n)).getByLabelText(/^Heading/)).toBeInTheDocument();
}
});
it("FAQ answers are multi-line and each question can be removed", async () => {
render(<PageEditor />);
await addBlock("FAQ");
await userEvent.click(within(block(1)).getByRole("button", { name: "Add question" }));
expect(within(block(1)).getByLabelText("Answer 1").tagName).toBe("TEXTAREA");
await userEvent.type(within(block(1)).getByLabelText("Question 2"), "Second?");
await userEvent.click(within(block(1)).getByRole("button", { name: "Remove question 1" }));
expect(within(block(1)).getByLabelText("Question 1")).toHaveValue("Second?");
expect(within(block(1)).queryByLabelText("Question 2")).not.toBeInTheDocument();
});
});
describe("errors", () => {
it("shows a field error once, next to its field", async () => {
pages.savePage.mockRejectedValue(new ApiError("blocks[0].heading: is required", 422));
render(<PageEditor />);
await userEvent.type(screen.getByLabelText(/^Title/), "Sale");
await addBlock("Hero");
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
expect(await within(block(1)).findByText("is required")).toBeInTheDocument();
expect(screen.getAllByText("is required")).toHaveLength(1);
});
it("shows an FAQ item error on that item", async () => {
pages.savePage.mockRejectedValue(new ApiError("blocks[0].items[1].answer: is required", 422));
render(<PageEditor />);
await userEvent.type(screen.getByLabelText(/^Title/), "Help");
await addBlock("FAQ");
await userEvent.click(within(block(1)).getByRole("button", { name: "Add question" }));
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
expect(await within(block(1)).findByText("is required")).toBeInTheDocument();
expect(screen.getAllByText("is required")).toHaveLength(1);
});
});
describe("images", () => {
it("shows the chosen file before saving", async () => {
render(<PageEditor />);
await addBlock("Hero");
await userEvent.upload(within(block(1)).getByLabelText("Block image"), png("hero.png"));
expect(within(block(1)).getByText(/hero\.png/)).toBeInTheDocument();
});
it("keeps a chosen image with its block when blocks are reordered", async () => {
pages.uploadPageImage.mockResolvedValue({ url: "https://cdn/cms-page/hero.png" });
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 addBlock("Hero");
await userEvent.upload(within(block(2)).getByLabelText("Block image"), png("hero.png"));
await userEvent.type(within(block(2)).getByLabelText(/^Heading/), "Big sale");
await userEvent.click(within(block(2)).getByRole("button", { name: "Move up" }));
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
await waitFor(() => expect(pages.savePage).toHaveBeenCalledTimes(1));
expect(pages.savePage.mock.calls[0][0].blocks).toEqual([
{ type: "HERO", imageUrl: "https://cdn/cms-page/hero.png", heading: "Big sale" },
{ type: "RICH_TEXT", html: "<p>x</p>" },
]);
});
it("drops a removed block's chosen image", async () => {
render(<PageEditor />);
await userEvent.type(screen.getByLabelText(/^Title/), "Sale");
await addBlock("Hero");
await userEvent.upload(within(block(1)).getByLabelText("Block image"), png("hero.png"));
await userEvent.click(within(block(1)).getByRole("button", { name: "Remove" }));
await addBlock("Rich text");
await userEvent.type(within(block(1)).getByLabelText(/^Content/), "<p>x</p>");
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
await waitFor(() => expect(pages.savePage).toHaveBeenCalledTimes(1));
expect(pages.uploadPageImage).not.toHaveBeenCalled();
});
it("retries only the uploads that failed", async () => {
pages.uploadPageImage
.mockResolvedValueOnce({ url: "https://cdn/cms-page/one.png" })
.mockRejectedValueOnce(new ApiError("Upload failed", 502))
.mockResolvedValue({ url: "https://cdn/cms-page/two.png" });
render(<PageEditor />);
await userEvent.type(screen.getByLabelText(/^Title/), "Sale");
await addBlock("Hero");
await userEvent.upload(within(block(1)).getByLabelText("Block image"), png("one.png"));
await userEvent.type(within(block(1)).getByLabelText(/^Heading/), "One");
await addBlock("Hero");
await userEvent.upload(within(block(2)).getByLabelText("Block image"), png("two.png"));
await userEvent.type(within(block(2)).getByLabelText(/^Heading/), "Two");
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
expect(await screen.findByText("Upload failed")).toBeInTheDocument();
expect(pages.savePage).not.toHaveBeenCalled();
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
await waitFor(() => expect(pages.savePage).toHaveBeenCalledTimes(1));
expect(pages.uploadPageImage.mock.calls.map((c) => c[0].fileName)).toEqual(["one.png", "two.png", "two.png"]);
expect(pages.savePage.mock.calls[0][0].blocks.map((b: { imageUrl?: string }) => b.imageUrl)).toEqual([
"https://cdn/cms-page/one.png",
"https://cdn/cms-page/two.png",
]);
});
it("uploads an image inserted into rich text straight away", async () => {
pages.uploadPageImage.mockResolvedValue({ url: "https://cdn/cms-page/inline.png" });
render(<PageEditor />);
await addBlock("Rich text");
await userEvent.click(within(block(1)).getByRole("button", { name: "Insert image" }));
await waitFor(() => expect(pages.uploadPageImage).toHaveBeenCalledTimes(1));
expect(pages.uploadPageImage.mock.calls[0][0]).toMatchObject({ fileName: "inline.png", fileType: "image/png" });
await waitFor(() => expect(within(block(1)).getByLabelText(/^Content/)).toHaveValue('<img src="https://cdn/cms-page/inline.png">'));
});
});
describe("existing page", () => {
it("lets the slug be renamed", async () => {
pages.getPage.mockResolvedValue(saved);
render(<PageEditor pageId={9} />);
await screen.findByDisplayValue("About us");
await userEvent.clear(screen.getByLabelText(/^Slug/));
await userEvent.type(screen.getByLabelText(/^Slug/), "our-story");
await userEvent.click(screen.getByRole("button", { name: "Save page" }));
await waitFor(() => expect(pages.savePage).toHaveBeenCalledTimes(1));
expect(pages.savePage.mock.calls[0][0]).toMatchObject({ id: 9, slug: "our-story" });
});
});