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 { CollectionView } from "@/app/lib/collections"; const router = vi.hoisted(() => ({ replace: vi.fn(), push: vi.fn(), search: new URLSearchParams() })); vi.mock("next/navigation", () => ({ useRouter: () => router, useSearchParams: () => router.search })); const collections = vi.hoisted(() => ({ getCollection: vi.fn(), saveCollection: vi.fn(), deleteCollection: vi.fn(), previewCollection: vi.fn(), uploadCollectionImage: vi.fn(), })); vi.mock("@/app/lib/services/adminCollections", () => collections); const product = vi.hoisted(() => ({ getProductOptions: vi.fn(), listProductTags: vi.fn(), listProducts: vi.fn(), })); vi.mock("@/app/lib/services/adminProduct", () => product); import { ApiError } from "@/app/lib/clientApi"; import { CollectionForm } from "./CollectionForm"; const saved: CollectionView = { id: 9, slug: "newborn-essentials", title: "Newborn Essentials", type: "MANUAL", match: "ALL", sort: "MANUAL", status: "Y", rules: [], products: [], }; beforeEach(() => { Object.values(collections).forEach((f) => f.mockReset()); Object.values(product).forEach((f) => f.mockReset()); router.replace.mockReset(); router.push.mockReset(); router.search = new URLSearchParams(); product.getProductOptions.mockResolvedValue({ brands: [{ id: "3", code: "MOMCOZY", status: "Y" }], categories: [{ id: "7", code: "Bedding", status: "Y" }], priceTypes: [], }); product.listProductTags.mockResolvedValue(["newborn"]); product.listProducts.mockResolvedValue({ items: [ { id: "1", productCode: "WP-1", productName: "Wipes", productStatus: "Y" }, { id: "2", productCode: "WP-2", productName: "Wipes travel pack", productStatus: "N" }, ], total: 2, }); collections.previewCollection.mockResolvedValue({ count: 0, names: [] }); collections.saveCollection.mockResolvedValue(saved); }); async function addProduct(name: RegExp) { const picker = screen.getByRole("combobox", { name: "Add products" }); await userEvent.clear(picker); await userEvent.type(picker, "wip"); await userEvent.click(await screen.findByText(name)); } describe("CollectionForm — new manual collection", () => { it("fills the slug from the title, orders hand-picked products and saves them", async () => { render(); await userEvent.type(screen.getByLabelText(/^Title/), "Newborn Essentials"); expect(screen.getByLabelText(/^Slug/)).toHaveValue("newborn-essentials"); await addProduct(/^Wipes$/); await addProduct(/Wipes travel pack/); const list = screen.getByRole("list", { name: "Products in this collection" }); expect(within(list).getAllByRole("listitem").map((li) => li.textContent)).toEqual([ expect.stringContaining("WP-1"), expect.stringContaining("WP-2"), ]); expect(within(list).getByText(/hidden from the storefront/i)).toBeInTheDocument(); await userEvent.click(screen.getByRole("button", { name: "Move WP-2 up" })); await userEvent.click(screen.getByRole("button", { name: "Save collection" })); await waitFor(() => expect(collections.saveCollection).toHaveBeenCalledTimes(1)); expect(collections.saveCollection.mock.calls[0][0]).toMatchObject({ slug: "newborn-essentials", title: "Newborn Essentials", type: "MANUAL", sort: "MANUAL", status: "Y", rules: [], productIds: [2, 1], }); expect(router.replace).toHaveBeenCalledWith("/collections/9?saved=1"); expect(await screen.findByText("Collection saved")).toBeInTheDocument(); }); it("stops following the title once the slug is edited by hand", async () => { render(); await userEvent.type(screen.getByLabelText(/^Title/), "Newborn"); await userEvent.clear(screen.getByLabelText(/^Slug/)); await userEvent.type(screen.getByLabelText(/^Slug/), "baby"); await userEvent.type(screen.getByLabelText(/^Title/), " Gear"); expect(screen.getByLabelText(/^Slug/)).toHaveValue("baby"); }); it("removes a product from the list", async () => { render(); await addProduct(/^Wipes$/); await userEvent.click(screen.getByRole("button", { name: "Remove WP-1" })); expect(screen.queryByRole("list", { name: "Products in this collection" })).not.toBeInTheDocument(); }); }); describe("CollectionForm — new automatic collection", () => { it("builds conditions, previews the match and saves the rules", async () => { collections.previewCollection.mockResolvedValue({ count: 4, names: ["Bottle", "Pump"] }); render(); await userEvent.type(screen.getByLabelText(/^Title/), "Momcozy newborn"); await userEvent.click(screen.getByRole("radio", { name: /automatic/i })); await userEvent.type(screen.getByRole("combobox", { name: "Condition 1 value" }), "newborn"); await userEvent.click(screen.getByRole("button", { name: "Add condition" })); await userEvent.click(screen.getByRole("combobox", { name: "Condition 2 field" })); await userEvent.click(await screen.findByRole("option", { name: "Brand" })); await userEvent.click(screen.getByRole("combobox", { name: "Condition 2 value" })); await userEvent.click(await screen.findByRole("option", { name: "MOMCOZY" })); await userEvent.click(screen.getByRole("radio", { name: /any condition/i })); await userEvent.click(screen.getByRole("combobox", { name: "Sort products" })); await userEvent.click(await screen.findByRole("option", { name: "Price, low to high" })); // The preview is debounced: wait until it has seen the finished draft. await waitFor(() => expect(collections.previewCollection.mock.calls.at(-1)![0]).toMatchObject({ type: "AUTOMATIC", match: "ANY", rules: [ { field: "TAG", value: "newborn" }, { field: "BRAND", value: "3" }, ], }), ); expect(await screen.findByText("Matches 4 products")).toBeInTheDocument(); expect(screen.getByText("Pump")).toBeInTheDocument(); await userEvent.click(screen.getByRole("button", { name: "Save collection" })); await waitFor(() => expect(collections.saveCollection).toHaveBeenCalledTimes(1)); expect(collections.saveCollection.mock.calls[0][0]).toMatchObject({ type: "AUTOMATIC", match: "ANY", sort: "PRICE_ASC", rules: [ { field: "TAG", value: "newborn" }, { field: "BRAND", value: "3" }, ], productIds: [], }); }); it("a condition without a value blocks the save and says so under it", async () => { render(); await userEvent.type(screen.getByLabelText(/^Title/), "Toddler"); await userEvent.click(screen.getByRole("radio", { name: /automatic/i })); await userEvent.click(screen.getByRole("button", { name: "Save collection" })); expect(collections.saveCollection).not.toHaveBeenCalled(); expect(screen.getByText("Choose a value")).toBeInTheDocument(); }); }); describe("CollectionForm — errors, edit and delete", () => { it("puts a server field error under the field it names", async () => { collections.saveCollection.mockRejectedValue(new ApiError("slug: another collection already uses newborn", 422)); render(); await userEvent.type(screen.getByLabelText(/^Title/), "Newborn"); await userEvent.click(screen.getByRole("button", { name: "Save collection" })); expect(await screen.findByText("another collection already uses newborn")).toBeInTheDocument(); expect(screen.getByLabelText(/^Slug/)).toHaveAttribute("aria-invalid", "true"); expect(router.replace).not.toHaveBeenCalled(); }); it("loads a saved collection with its type fixed, and deletes it after confirmation", async () => { collections.getCollection.mockResolvedValue({ ...saved, id: 5, title: "Toddler", slug: "toddler", products: [{ id: 1, code: "WP-1", name: "Wipes", status: "Y" }], }); collections.deleteCollection.mockResolvedValue({ ok: true }); render(); expect(await screen.findByDisplayValue("Toddler")).toBeInTheDocument(); expect(collections.getCollection).toHaveBeenCalledWith(5); expect(screen.queryByRole("radio", { name: /automatic/i })).not.toBeInTheDocument(); expect(screen.getByText(/manual — the type is fixed once created/i)).toBeInTheDocument(); expect(screen.getByText("WP-1", { exact: false })).toBeInTheDocument(); await userEvent.click(screen.getByRole("button", { name: "Delete collection" })); expect(collections.deleteCollection).not.toHaveBeenCalled(); await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" })); await waitFor(() => expect(collections.deleteCollection).toHaveBeenCalledWith(5)); expect(router.push).toHaveBeenCalledWith("/collections"); }); it("uploads a chosen image on save, before saving the collection with its URL", async () => { collections.uploadCollectionImage.mockResolvedValue({ url: "https://cdn/collection/hero.png" }); render(); await userEvent.type(screen.getByLabelText(/^Title/), "Newborn"); await userEvent.upload(screen.getByLabelText("Collection image"), new File(["png"], "hero.png", { type: "image/png" })); expect(collections.uploadCollectionImage).not.toHaveBeenCalled(); await userEvent.click(screen.getByRole("button", { name: "Save collection" })); await waitFor(() => expect(collections.saveCollection).toHaveBeenCalledTimes(1)); expect(collections.uploadCollectionImage).toHaveBeenCalledWith({ fileName: "hero.png", fileType: "image/png", base: expect.any(String) }); expect(collections.uploadCollectionImage.mock.invocationCallOrder[0]).toBeLessThan( collections.saveCollection.mock.invocationCallOrder[0], ); expect(collections.saveCollection.mock.calls[0][0].imageUrl).toBe("https://cdn/collection/hero.png"); }); it("a server error on a product row shows under the product list (Refuter #1)", async () => { collections.saveCollection.mockRejectedValue(new ApiError("productIds[0]: unknown product 1", 422)); render(); await userEvent.type(screen.getByLabelText(/^Title/), "Picks"); await addProduct(/^Wipes$/); await userEvent.click(screen.getByRole("button", { name: "Save collection" })); expect(await screen.findByText("unknown product 1")).toBeInTheDocument(); }); it("a server error on a field the form does not show becomes the summary (Refuter #1)", async () => { collections.saveCollection.mockRejectedValue(new ApiError("status: must be Y or N", 422)); render(); await userEvent.type(screen.getByLabelText(/^Title/), "Picks"); await userEvent.click(screen.getByRole("button", { name: "Save collection" })); expect(await screen.findByText(/must be Y or N/)).toBeInTheDocument(); }); it("a retry after a failed save reuses the uploaded image instead of uploading again (Refuter #2)", async () => { collections.uploadCollectionImage.mockResolvedValue({ url: "https://cdn/collection/hero.png" }); collections.saveCollection.mockRejectedValueOnce(new ApiError("slug: another collection already uses newborn", 422)); render(); await userEvent.type(screen.getByLabelText(/^Title/), "Newborn"); await userEvent.upload(screen.getByLabelText("Collection image"), new File(["png"], "hero.png", { type: "image/png" })); await userEvent.click(screen.getByRole("button", { name: "Save collection" })); await screen.findByText("another collection already uses newborn"); await userEvent.click(screen.getByRole("button", { name: "Save collection" })); await waitFor(() => expect(collections.saveCollection).toHaveBeenCalledTimes(2)); expect(collections.uploadCollectionImage).toHaveBeenCalledTimes(1); expect(collections.saveCollection.mock.calls[1][0].imageUrl).toBe("https://cdn/collection/hero.png"); }); it("the edit page opened right after creating says the collection was saved", async () => { router.search = new URLSearchParams("saved=1"); collections.getCollection.mockResolvedValue({ ...saved, id: 9 }); render(); expect(await screen.findByText("Collection saved")).toBeInTheDocument(); }); });