Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/screens/projects/PipelineAdminPage.test.tsx
T

246 lines
13 KiB
TypeScript

// WF-P8 S07 — PipelineAdminPage unit test. Fixture via the real
// buildPipelineAdminVM; interactions asserted on the injected onSubmit.
// The column config moved to S04 (BoardSettingsPage.test.tsx); what is left
// here is the board table, its filters and the create dialog incl. S07a.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildPipelineAdminVM, type PipelineAdminData, type PipelineAdminItem } from "@hivegrid/view-models";
import { filterBoards, PipelineAdminPage } from "./PipelineAdminPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
// Radix selects are not interactable in jsdom; swap ~/ui Select for a native
// one so the create dialog's type field can be driven and asserted.
vi.mock("~/ui/components/Select", () => {
const Select = ({ value, onValueChange, label, error, errorText, children, ...rest }: any) => (
<div data-ui-id={rest["data-ui-id"]}>
<select
aria-label={typeof label === "string" ? label : "select"}
value={value ?? ""}
onChange={(e: any) => onValueChange?.(e.target.value)}
data-ui-id={rest["data-ui-id"] ? `${rest["data-ui-id"]}.native` : undefined}
>
<option value="" />
{children}
</select>
{error && errorText ? <span data-ui-id={rest["data-ui-id"] ? `${rest["data-ui-id"]}.errorText` : undefined}>{errorText}</span> : null}
</div>
);
Select.Item = ({ value, children }: any) => <option value={value}>{children}</option>;
return { Select };
});
// Radix dropdowns neither open nor provide their menu context in jsdom, so the
// row actions would be unreachable. Both the SubframeCore wrapper and the ~/ui
// menu are swapped for plain passthroughs; the entries stay real buttons.
vi.mock("@subframe/core", async () => {
const actual = await vi.importActual<Record<string, unknown>>("@subframe/core");
const Pass = ({ children }: { children?: React.ReactNode }) => <>{children}</>;
return { ...actual, DropdownMenu: { Root: Pass, Trigger: Pass, Portal: Pass, Content: Pass, Item: Pass } };
});
// Same reason for the facet menus of the filter bar.
vi.mock("~/ui/components/DropdownMenuMultiSelect", () => {
const DropdownMenuMultiSelect = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownItem = ({ children, onClick, selected, ...rest }: any) => (
<button type="button" onClick={onClick} aria-pressed={Boolean(selected)} data-ui-id={rest["data-ui-id"]}>
{children}
</button>
);
DropdownMenuMultiSelect.DropdownCustomItem = ({ children }: any) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownUserItem = ({ title }: any) => <div>{title}</div>;
DropdownMenuMultiSelect.DropdownDivider = () => <hr />;
return { DropdownMenuMultiSelect };
});
vi.mock("~/ui/components/DropdownMenu", () => {
const DropdownMenu = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
DropdownMenu.DropdownItem = ({ children, onSelect, ...rest }: any) => (
<button type="button" onClick={() => onSelect?.()} data-ui-id={rest["data-ui-id"]}>
{children}
</button>
);
DropdownMenu.DropdownDivider = () => <hr />;
return { DropdownMenu };
});
const byUiId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLElement;
type FixturePipeline = Parameters<typeof buildPipelineAdminVM>[0]["pipelines"][number];
const salesBoard: FixturePipeline = {
id: "pl1",
name: "Sales",
typHint: "sales",
isDefault: true,
projectCount: 11,
updatedAtIso: "2026-07-12T06:12:00.000Z",
stages: [
{ id: "s1", name: "Neu", stageKind: "offen", winProbability: 10, color: "#000", position: 10, projectCount: 4 },
{ id: "s2", name: "Gewonnen", stageKind: "gewonnen", winProbability: 100, color: "#0a0", position: 20, projectCount: 5 },
{ id: "s3", name: "Verloren", stageKind: "verloren", winProbability: 0, color: "#a00", position: 30, projectCount: 2 },
],
accessRules: [],
fieldConfigs: [],
};
// No won/lost stage -> the VM calls this a draft; one deny rule -> restricted.
const draftBoard: FixturePipeline = {
id: "pl2",
name: "Eigenes Board",
typHint: "custom",
isDefault: false,
projectCount: 0,
stages: [{ id: "s9", name: "Neu", stageKind: "offen", winProbability: 0, color: "#666", position: 10, projectCount: 0 }],
accessRules: [{ id: "a1", principalType: "group", principalId: "grp-montage", kannSehen: false, kannBearbeiten: false }],
fieldConfigs: [],
};
function adminData(pipelines: FixturePipeline[] = [salesBoard, draftBoard]): PipelineAdminData {
const vm = buildPipelineAdminVM({ canAdmin: true, pipelines });
if (vm.status !== "ready") throw new Error("fixture not ready");
return vm.data;
}
const baseProps = {
lostReasonsHref: "/acme/admin/pipelines/lost-reasons",
settingsHref: (id: string) => `/acme/admin/pipelines/${id}`,
};
function renderPage(data = adminData()) {
const onSubmit = vi.fn();
render(<PipelineAdminPage {...baseProps} data={data} submitting={false} actions={{ onSubmit }} />);
return onSubmit;
}
describe("PipelineAdminPage", () => {
it("points the header settings button at the default board", () => {
renderPage();
// The export's button names no board; the default one is the only sensible
// target, and it is the board the footer line already calls out.
expect(byUiId("ui.projects.admin.headerSettings").getAttribute("href")).toBe("/acme/admin/pipelines/pl1");
});
it("falls back to the first board when none is marked as the default", () => {
renderPage(adminData([{ ...draftBoard, isDefault: false }]));
expect(byUiId("ui.projects.admin.headerSettings").getAttribute("href")).toBe("/acme/admin/pipelines/pl2");
});
it("renders one row per board with counts, access and status", () => {
renderPage();
expect(byUiId("ui.projects.admin.list")).toBeTruthy();
expect(screen.getByText("Sales")).toBeTruthy();
expect(byUiId("ui.projects.admin.row.pl1.projects").textContent).toBe("11");
// getAllByText: the mocked native filter selects render the same labels as
// <option> text, so a row badge is never the only match.
// A board without a won and a lost column cannot complete a project.
expect(screen.getAllByText("projects.boardSettings.status.draft").length).toBeGreaterThan(0);
expect(screen.getAllByText("projects.admin.accessScope.restricted").length).toBeGreaterThan(0);
expect(screen.getAllByText("projects.admin.accessScope.everyone").length).toBeGreaterThan(0);
});
it("links every row to its own S04 settings page", () => {
renderPage();
expect(byUiId("ui.projects.admin.row.pl1.open").getAttribute("href")).toBe("/acme/admin/pipelines/pl1");
expect(byUiId("ui.projects.admin.row.pl1.settings").getAttribute("href")).toBe("/acme/admin/pipelines/pl1");
});
it("names the default board in the footer line", () => {
renderPage();
expect(byUiId("ui.projects.admin.footer").textContent).toContain("projects.admin.footerLine");
});
it("shows an empty state when no board is left", () => {
renderPage(adminData([]));
expect(byUiId("ui.projects.admin.empty")).toBeTruthy();
expect(byUiId("ui.projects.admin.list")).toBeNull();
});
it("archives and duplicates a board from the row menu", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.admin.row.pl1.archive"));
expect(onSubmit).toHaveBeenCalledWith("archivePipeline", { pipelineId: "pl1" });
fireEvent.click(byUiId("ui.projects.admin.row.pl1.duplicate"));
expect(onSubmit).toHaveBeenCalledWith("duplicatePipeline", expect.objectContaining({ pipelineId: "pl1" }));
});
it("filters by search, type, status, access and rules", () => {
const boards: readonly PipelineAdminItem[] = adminData().pipelines;
const names = (result: readonly { name: string }[]) => result.map((row) => row.name);
const all = { search: "", typ: new Set<string>(), status: new Set<string>(), access: new Set<string>(), rules: new Set<string>() };
expect(names(filterBoards(boards, all))).toEqual(["Sales", "Eigenes Board"]);
expect(names(filterBoards(boards, { ...all, search: "eigen" }))).toEqual(["Eigenes Board"]);
expect(names(filterBoards(boards, { ...all, typ: new Set(["sales"]) }))).toEqual(["Sales"]);
expect(names(filterBoards(boards, { ...all, status: new Set(["draft"]) }))).toEqual(["Eigenes Board"]);
expect(names(filterBoards(boards, { ...all, access: new Set(["everyone"]) }))).toEqual(["Sales"]);
// "Regeln" asks whether a board carries access rules at all, which is not
// the same question as the access scope (that one counts denying rules).
expect(names(filterBoards(boards, { ...all, rules: new Set(["withRules"]) }))).toEqual(["Eigenes Board"]);
expect(names(filterBoards(boards, { ...all, rules: new Set(["withoutRules"]) }))).toEqual(["Sales"]);
// Several values inside one facet are OR-ed, not AND-ed.
expect(names(filterBoards(boards, { ...all, status: new Set(["active", "draft"]) }))).toEqual(["Sales", "Eigenes Board"]);
expect(filterBoards(boards, { ...all, search: "gibtsnicht" })).toEqual([]);
});
it("creates a board with default columns once name and type are valid", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.admin.newPipeline.open"));
fireEvent.change(byUiId("ui.projects.admin.newPipeline.name"), { target: { value: "Service" } });
fireEvent.change(byUiId("ui.projects.admin.newPipeline.typ.native"), { target: { value: "custom" } });
fireEvent.click(byUiId("ui.projects.admin.newPipeline.create"));
expect(onSubmit).toHaveBeenCalledWith("createPipeline", expect.objectContaining({ name: "Service", typHint: "custom" }));
expect(byUiId("ui.projects.admin.newPipeline.error")).toBeNull();
});
it("shows the S07a error state when no board type is chosen", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.admin.newPipeline.open"));
fireEvent.change(byUiId("ui.projects.admin.newPipeline.name"), { target: { value: "Service" } });
fireEvent.click(byUiId("ui.projects.admin.newPipeline.create"));
expect(onSubmit).not.toHaveBeenCalled();
expect(byUiId("ui.projects.admin.newPipeline.error")).toBeTruthy();
expect(screen.getByText("projects.admin.createDialog.createError")).toBeTruthy();
expect(screen.getByText("projects.admin.createDialog.typRequired")).toBeTruthy();
});
it("flags a duplicate board name against the loaded board list", () => {
const onSubmit = renderPage();
fireEvent.click(byUiId("ui.projects.admin.newPipeline.open"));
fireEvent.change(byUiId("ui.projects.admin.newPipeline.name"), { target: { value: " sales " } });
fireEvent.change(byUiId("ui.projects.admin.newPipeline.typ.native"), { target: { value: "sales" } });
fireEvent.click(byUiId("ui.projects.admin.newPipeline.create"));
expect(onSubmit).not.toHaveBeenCalled();
expect(screen.getByText("projects.admin.createDialog.nameDuplicate")).toBeTruthy();
// Correcting the name clears the field message.
fireEvent.change(byUiId("ui.projects.admin.newPipeline.name"), { target: { value: "Service" } });
expect(screen.queryByText("projects.admin.createDialog.nameDuplicate")).toBeNull();
});
it("maps a server-side duplicate error onto the name field and keeps the dialog open", () => {
const onSubmit = vi.fn();
const props = { ...baseProps, data: adminData(), actions: { onSubmit } };
const view = render(<PipelineAdminPage {...props} submitting={false} errorKey={null} />);
fireEvent.click(byUiId("ui.projects.admin.newPipeline.open"));
fireEvent.change(byUiId("ui.projects.admin.newPipeline.name"), { target: { value: "Service" } });
fireEvent.change(byUiId("ui.projects.admin.newPipeline.typ.native"), { target: { value: "custom" } });
fireEvent.click(byUiId("ui.projects.admin.newPipeline.create"));
expect(onSubmit).toHaveBeenCalled();
// Simulate the POST round-trip ending in a duplicate-name server error.
view.rerender(<PipelineAdminPage {...props} submitting errorKey={null} />);
view.rerender(<PipelineAdminPage {...props} submitting={false} errorKey="projects.error.pipelineNameDuplicate" />);
expect(byUiId("ui.projects.admin.newPipeline.error")).toBeTruthy();
expect(screen.getByText("projects.admin.createDialog.nameDuplicate")).toBeTruthy();
});
it("renders the info box about configuring columns and access afterwards", () => {
renderPage();
fireEvent.click(byUiId("ui.projects.admin.newPipeline.open"));
expect(byUiId("ui.projects.admin.newPipeline.info")).toBeTruthy();
expect(screen.getByText("projects.admin.createDialog.infoTitle")).toBeTruthy();
expect(screen.getByText("projects.admin.createDialog.infoBody")).toBeTruthy();
});
});