Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/ui/commandPalettes/CommandPalette.test.tsx
T

534 lines
21 KiB
TypeScript

import "@testing-library/jest-dom";
import { act, fireEvent, render, screen, waitFor, type RenderResult } from "@testing-library/react";
import React from "react";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { GlobalSearchEntityType, GlobalSearchResponse } from "~/services/search/globalSearch.server";
import { UI_ACTION_IDS, UI_SURFACE_IDS } from "~/application/ui/uiRegistry";
import type { ScopedCommandAction } from "~/services/command-registry/commandRegistry";
import CommandPalette from "./CommandPalette";
type FetcherMock = {
state: "idle" | "loading";
data?: GlobalSearchResponse | { error: string };
load: ReturnType<typeof vi.fn>;
submit: ReturnType<typeof vi.fn>;
};
type CommandPaletteTestState = {
navigate: ReturnType<typeof vi.fn>;
openWindow: ReturnType<typeof vi.fn>;
getCommandRegistryActions: ReturnType<typeof vi.fn>;
useAppOrAdminData: ReturnType<typeof vi.fn>;
useRootData: ReturnType<typeof vi.fn>;
actionFetcher: FetcherMock;
searchFetcher: FetcherMock;
recentFetcher: FetcherMock;
};
declare global {
var __commandPaletteTest: CommandPaletteTestState;
}
function createFetcher(): FetcherMock {
return { state: "idle", data: undefined, load: vi.fn().mockResolvedValue(undefined), submit: vi.fn() };
}
globalThis.__commandPaletteTest = {
navigate: vi.fn(),
openWindow: vi.fn(),
getCommandRegistryActions: vi.fn(),
useAppOrAdminData: vi.fn(),
useRootData: vi.fn(),
actionFetcher: createFetcher(),
searchFetcher: createFetcher(),
recentFetcher: createFetcher(),
};
globalThis.ResizeObserver =
globalThis.ResizeObserver ??
class ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
};
HTMLElement.prototype.scrollIntoView = HTMLElement.prototype.scrollIntoView ?? vi.fn();
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (value: string) => value, i18n: { language: "en" } }),
}));
vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
...actual,
useFetcher: (options?: { key?: string }) => {
if (options?.key === "command-palette-search") return globalThis.__commandPaletteTest.searchFetcher;
if (options?.key === "command-palette-recent") return globalThis.__commandPaletteTest.recentFetcher;
return globalThis.__commandPaletteTest.actionFetcher;
},
useNavigate: () => globalThis.__commandPaletteTest.navigate,
};
});
vi.mock("~/utils/data/useAppOrAdminData", () => ({
useAppOrAdminData: () => globalThis.__commandPaletteTest.useAppOrAdminData(),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => globalThis.__commandPaletteTest.useRootData(),
}));
vi.mock("~/services/command-registry/commandRegistry", () => ({
getCommandRegistryActions: (...args: unknown[]) => globalThis.__commandPaletteTest.getCommandRegistryActions(...args),
}));
const appData = { currentTenant: { slug: "acme" }, permissions: ["search.use"] };
const rootData = { csrf: "csrf-token", appConfiguration: { app: { features: {} } } };
function paletteElement(props?: Partial<React.ComponentProps<typeof CommandPalette>>) {
return (
<CommandPalette layout="app" {...props}>
<button data-ui-id={UI_ACTION_IDS.search}>Open search</button>
<button data-ui-id={UI_ACTION_IDS.searchMobile}>Open mobile search</button>
<div>Palette child</div>
</CommandPalette>
);
}
function renderPalette(props?: Partial<React.ComponentProps<typeof CommandPalette>>) {
return render(paletteElement(props));
}
function openPalette() {
fireEvent.keyDown(window, { key: "k", metaKey: true });
}
function openPaletteWithCtrl() {
fireEvent.keyDown(window, { key: "k", ctrlKey: true });
}
function searchInput() {
return document.querySelector<HTMLInputElement>(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteSearch}"]`)!;
}
function lastSearchRequest() {
const url = globalThis.__commandPaletteTest.searchFetcher.load.mock.calls.at(-1)?.[0] as string;
return new URL(url, "https://app.example.test");
}
function resultRow(entityType: GlobalSearchEntityType, entityId: string) {
const normalizedId = entityId
.split(/[^a-zA-Z0-9]+/u)
.filter(Boolean)
.map((word, index) => (index === 0 ? word.toLowerCase() : `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`))
.join("");
return document.querySelector<HTMLElement>(`[data-ui-id="ui.surface.commandPalette.result.${entityType}.${normalizedId}"]`)!;
}
function searchResponse(requestUrl: URL, overrides: Partial<GlobalSearchResponse> = {}): GlobalSearchResponse {
const query = requestUrl.searchParams.get("q") ?? "";
const requestedEntityTypes = requestUrl.searchParams.getAll("type") as GlobalSearchEntityType[];
const requestId = requestUrl.searchParams.get("requestId");
const limit = requestUrl.searchParams.get("limit") ?? "20";
return {
query,
requestedEntityTypes,
requestId,
requestKey: `${encodeURIComponent(query)}|${requestedEntityTypes.join(",") || "*"}|${limit}`,
results: [],
recentSearches: [],
hiddenEntityTypes: [],
latencyHint: "Search index updates can take up to 10 seconds.",
...overrides,
};
}
async function sendSearchQuery(query: string) {
vi.useFakeTimers();
fireEvent.change(searchInput(), { target: { value: query } });
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
return lastSearchRequest();
}
async function applySearchResponse(
view: RenderResult,
response: GlobalSearchResponse | { error: string },
props?: Partial<React.ComponentProps<typeof CommandPalette>>
) {
globalThis.__commandPaletteTest.searchFetcher.state = "idle";
globalThis.__commandPaletteTest.searchFetcher.data = response;
view.rerender(paletteElement(props));
await act(async () => undefined);
}
describe("CommandPalette", () => {
beforeAll(async () => {
await import("./CommandPaletteDialog");
}, 60000);
beforeEach(() => {
const state = globalThis.__commandPaletteTest;
state.navigate.mockReset();
state.openWindow.mockReset();
state.getCommandRegistryActions.mockReset();
state.useAppOrAdminData.mockReset();
state.useRootData.mockReset();
state.actionFetcher = createFetcher();
state.searchFetcher = createFetcher();
state.recentFetcher = createFetcher();
state.useAppOrAdminData.mockReturnValue(appData);
state.useRootData.mockReturnValue(rootData);
state.getCommandRegistryActions.mockReturnValue([
{ id: "registry-dashboard", name: "Dashboard", subtitle: "App", perform: vi.fn(), scope: { layout: "app", tenantSlug: "acme" } },
{ id: "registry-profile", name: "Profile", subtitle: "Settings", perform: vi.fn(), scope: { layout: "app", tenantSlug: "acme" } },
]);
vi.spyOn(window, "open").mockImplementation(state.openWindow);
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
it("passes registry actions through and opens from Cmd+K or Ctrl+K", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("Dashboard", undefined, { timeout: 4000 });
expect(globalThis.__commandPaletteTest.getCommandRegistryActions).toHaveBeenCalledWith(
expect.objectContaining({ layout: "app", navigate: globalThis.__commandPaletteTest.navigate, appData, rootData })
);
expect(screen.getByText("Palette child")).toBeInTheDocument();
expect(document.querySelector('[data-ui-id="ui.surface.commandPalette.action.registryDashboard"]')).toBeInTheDocument();
fireEvent.keyDown(window, { key: "k", metaKey: true });
expect(screen.queryByText("Dashboard")).not.toBeInTheDocument();
openPaletteWithCtrl();
expect(await screen.findByText("Dashboard")).toBeInTheDocument();
view.unmount();
});
it("uses custom actions without consulting the registry", async () => {
const customActions: ScopedCommandAction[] = [{ id: "custom-action", name: "Custom Action", perform: vi.fn(), scope: { layout: "app" } }];
renderPalette({ actions: customActions });
openPalette();
expect(await screen.findByText("Custom Action")).toBeInTheDocument();
expect(globalThis.__commandPaletteTest.getCommandRegistryActions).not.toHaveBeenCalled();
});
it("debounces global search, requests 20 results, and does not reload after accepting a response", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
await waitFor(() => expect(globalThis.__commandPaletteTest.searchFetcher.load).toHaveBeenCalledTimes(1));
vi.useFakeTimers();
fireEvent.change(searchInput(), { target: { value: "solar" } });
await act(async () => {
await vi.advanceTimersByTimeAsync(299);
});
expect(globalThis.__commandPaletteTest.searchFetcher.load).toHaveBeenCalledTimes(1);
await act(async () => {
await vi.advanceTimersByTimeAsync(1);
});
vi.useRealTimers();
const request = lastSearchRequest();
expect(request.pathname).toContain("/search/api");
expect(request.searchParams.get("q")).toBe("solar");
expect(request.searchParams.get("limit")).toBe("20");
expect(request.searchParams.getAll("type")).toEqual(["contact", "company", "lead", "project", "file", "task", "employee", "user"]);
expect(request.searchParams.get("requestId")).toMatch(/^spotlight-/);
await applySearchResponse(view, searchResponse(request));
await screen.findByText("search.results.empty");
await act(async () => undefined);
expect(globalThis.__commandPaletteTest.searchFetcher.load).toHaveBeenCalledTimes(2);
});
it("rejects a stale response after filters change and renders the current grouped response with permission hint", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const firstRequest = await sendSearchQuery("solar");
vi.useFakeTimers();
fireEvent.click(screen.getByRole("button", { name: "search.entities.user" }));
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
const currentRequest = lastSearchRequest();
expect(currentRequest.searchParams.get("requestId")).not.toBe(firstRequest.searchParams.get("requestId"));
expect(currentRequest.searchParams.getAll("type")).toEqual(["user"]);
await applySearchResponse(
view,
searchResponse(firstRequest, {
results: [
{
id: "stale",
entityType: "project",
title: "Stale solar project",
subtitle: "P-0",
href: "/projects/stale",
permissionSubject: "projects.read_all",
updatedAt: null,
},
],
})
);
expect(screen.queryByText("Stale solar project")).not.toBeInTheDocument();
await applySearchResponse(
view,
searchResponse(currentRequest, {
hiddenEntityTypes: ["user"],
results: [
{
id: "project-1",
entityType: "project",
title: "Solar roof",
subtitle: "P-100",
href: "/projects/project-1",
permissionSubject: "projects.read_all",
updatedAt: "2026-07-12T08:00:00.000Z",
},
{
id: "contact-1",
entityType: "contact",
title: "Solaris GmbH",
subtitle: "info@solaris.test",
href: "/contacts/contact-1",
permissionSubject: "crm.read_all",
updatedAt: null,
},
],
})
);
await waitFor(() => expect(resultRow("project", "project-1")).toHaveTextContent("Solar roof"));
const headings = [...document.querySelectorAll("[cmdk-group-heading]")].map((node) => node.textContent);
expect(headings.indexOf("search.entities.contact")).toBeLessThan(headings.indexOf("search.entities.project"));
expect(screen.getByText("search.results.hidden")).toBeInTheDocument();
expect(document.querySelector("mark")).toHaveTextContent(/solar/i);
});
it("narrows to a single category on the first tile click and resets to all when the last one is deselected", async () => {
renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
await sendSearchQuery("solar");
async function clickTile(entityType: GlobalSearchEntityType) {
vi.useFakeTimers();
fireEvent.click(screen.getByRole("button", { name: `search.entities.${entityType}` }));
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
return lastSearchRequest().searchParams.getAll("type");
}
// All selected by default: first click focuses on the clicked category only.
expect(await clickTile("project")).toEqual(["project"]);
// Further clicks toggle categories in canonical order.
expect(await clickTile("contact")).toEqual(["contact", "project"]);
expect(await clickTile("contact")).toEqual(["project"]);
// Deselecting the last active category resets back to all.
expect(await clickTile("project")).toEqual(["contact", "company", "lead", "project", "file", "task", "employee", "user"]);
});
it("shows loading, error, empty, short-query, and recent-search states", async () => {
const view = renderPalette();
openPalette();
expect(await screen.findByText("search.command.minimumCharacters")).toBeInTheDocument();
const recentRequest = lastSearchRequest();
await applySearchResponse(
view,
searchResponse(recentRequest, {
recentSearches: [{ id: "recent-1", queryText: "heat pump", entityTypes: ["project", "task"], resultCount: 4, createdAt: "2026-07-12T08:00:00.000Z" }],
})
);
expect(await screen.findByText("heat pump")).toBeInTheDocument();
vi.useFakeTimers();
fireEvent.change(searchInput(), { target: { value: "nothing" } });
globalThis.__commandPaletteTest.searchFetcher.state = "loading";
view.rerender(paletteElement());
expect(screen.getByText("search.command.loading")).toBeInTheDocument();
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
const emptyRequest = lastSearchRequest();
await applySearchResponse(view, searchResponse(emptyRequest));
expect(await screen.findByText("search.results.empty")).toBeInTheDocument();
await applySearchResponse(view, { error: "invalid_request_id" });
expect(await screen.findByText("search.command.error")).toBeInTheDocument();
const requestsBeforeRetry = globalThis.__commandPaletteTest.searchFetcher.load.mock.calls.length;
vi.useFakeTimers();
fireEvent.click(screen.getByRole("button", { name: "shared.retry" }));
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
expect(globalThis.__commandPaletteTest.searchFetcher.load).toHaveBeenCalledTimes(requestsBeforeRetry + 1);
});
it("records a committed selection without waiting before Enter navigates in the same tab", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const request = await sendSearchQuery("anna");
await applySearchResponse(
view,
searchResponse(request, {
results: [
{
id: "contact-1",
entityType: "contact",
title: "Anna Becker",
subtitle: "anna@example.test",
href: "/contacts/contact-1",
permissionSubject: "crm.read_all",
updatedAt: null,
},
],
})
);
await waitFor(() => expect(resultRow("contact", "contact-1")).toHaveTextContent("Anna Becker"));
const row = resultRow("contact", "contact-1");
row.focus();
fireEvent.keyDown(row, { key: "Enter" });
expect(globalThis.__commandPaletteTest.navigate).toHaveBeenCalledWith("/contacts/contact-1");
expect(globalThis.__commandPaletteTest.recentFetcher.submit).toHaveBeenCalledTimes(1);
const [form, options] = globalThis.__commandPaletteTest.recentFetcher.submit.mock.calls[0]!;
expect(form).toBeInstanceOf(FormData);
expect((form as FormData).get("intent")).toBe("recordRecent");
expect((form as FormData).get("query")).toBe("anna");
expect((form as FormData).get("selectedEntityType")).toBe("contact");
expect((form as FormData).get("selectedEntityId")).toBe("contact-1");
expect((form as FormData).get("csrf")).toBe("csrf-token");
expect(options).toEqual(expect.objectContaining({ method: "post", action: expect.stringContaining("/search/api") }));
});
it.each([
{ label: "Cmd", modifier: "metaKey" as const },
{ label: "Ctrl", modifier: "ctrlKey" as const },
])("opens the selected result in a new tab with $label+Enter", async ({ modifier }) => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const request = await sendSearchQuery("quote");
await applySearchResponse(
view,
searchResponse(request, {
results: [
{
id: "file-1",
entityType: "file",
title: "Quote.pdf",
subtitle: "application/pdf",
href: "/files/file-1",
permissionSubject: "files.read_all",
updatedAt: null,
},
],
})
);
await waitFor(() => expect(resultRow("file", "file-1")).toHaveTextContent("Quote.pdf"));
const row = resultRow("file", "file-1");
row.focus();
fireEvent.keyDown(row, { key: "Enter", [modifier]: true });
await waitFor(() => expect(globalThis.__commandPaletteTest.openWindow).toHaveBeenCalledWith("/files/file-1", "_blank", "noopener,noreferrer"));
expect(globalThis.__commandPaletteTest.navigate).not.toHaveBeenCalled();
});
it("loads one additional page inside the modal up to the 50-result cap", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const request = await sendSearchQuery("project");
const results = Array.from({ length: 20 }, (_, index) => ({
id: `project-${index}`,
entityType: "project" as const,
title: `Project ${index}`,
subtitle: `P-${index}`,
href: `/projects/project-${index}`,
permissionSubject: "projects.read_all",
updatedAt: null,
}));
await applySearchResponse(view, searchResponse(request, { results }));
const loadMore = await screen.findByRole("button", { name: "search.command.loadMore" });
vi.useFakeTimers();
fireEvent.click(loadMore);
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
const expandedRequest = lastSearchRequest();
expect(expandedRequest.searchParams.get("limit")).toBe("50");
await applySearchResponse(view, searchResponse(expandedRequest, { results }));
expect(screen.queryByRole("button", { name: "search.command.loadMore" })).not.toBeInTheDocument();
});
it("renders unique registry-backed UI IDs for the mobile/desktop Spotlight surfaces and rows", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const request = await sendSearchQuery("solar");
await applySearchResponse(
view,
searchResponse(request, {
results: [
{
id: "project-1",
entityType: "project",
title: "Solar roof",
subtitle: "P-100",
href: "/projects/project-1",
permissionSubject: "projects.read_all",
updatedAt: null,
},
],
})
);
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPalettePortal}"]`)).toHaveClass("h-dvh", "sm:h-auto");
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteSearch}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteFilters}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteResults}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteFooter}"]`)).toBeInTheDocument();
const ids = [...document.querySelectorAll("[data-ui-id]")].map((element) => element.getAttribute("data-ui-id"));
expect(new Set(ids).size).toBe(ids.length);
expect(ids).toContain("ui.surface.commandPalette.result.project.project1");
});
it("renders a safe action-only palette when app/root data is missing", async () => {
globalThis.__commandPaletteTest.useAppOrAdminData.mockReturnValue(undefined);
globalThis.__commandPaletteTest.useRootData.mockReturnValue(undefined);
globalThis.__commandPaletteTest.getCommandRegistryActions.mockReturnValue([]);
renderPalette();
openPalette();
expect(await screen.findByText("app.commands.empty.title")).toBeInTheDocument();
expect(globalThis.__commandPaletteTest.searchFetcher.load).not.toHaveBeenCalled();
});
});