Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

test(views): rewrite shared component tests in packages/views

Naiyuan Qingcc5e2e1712cf
diff --git a/apps/web/app/(dashboard)/issues/[id]/page.test.tsx b/apps/web/app/(dashboard)/issues/[id]/page.test.tsx
deleted file mode 100644
index 09469bec6a..0000000000
--- a/apps/web/app/(dashboard)/issues/[id]/page.test.tsx
+++ /dev/null
@@ -1,576 +0,0 @@
-import { Suspense, forwardRef, useRef, useState, useImperativeHandle } from "react";
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { render, screen, waitFor, act, fireEvent } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import type { Issue, Comment, TimelineEntry } from "@multica/core/types";
-import { WorkspaceIdProvider } from "@multica/core/hooks";
-
-// Mock next/navigation
-vi.mock("next/navigation", () => ({
- useRouter: () => ({ push: vi.fn() }),
- usePathname: () => "/issues/issue-1",
-}));
-
-// Mock next/link
-vi.mock("next/link", () => ({
- default: ({
- children,
- href,
- ...props
- }: {
- children: React.ReactNode;
- href: string;
- [key: string]: any;
- }) => (
- <a href={href} {...props}>
- {children}
- </a>
- ),
-}));
-
-// Mock auth store
-vi.mock("@/platform/auth", () => ({
- useAuthStore: (selector: (s: any) => any) =>
- selector({
- user: { id: "user-1", name: "Test User", email: "[email protected]" },
- isLoading: false,
- }),
-}));
-
-// Mock @multica/core/workspace (used by @multica/views components)
-vi.mock("@multica/core/workspace", () => ({
- useWorkspaceStore: Object.assign(
- (selector: (s: any) => any) =>
- selector({
- workspace: { id: "ws-1", name: "Test WS" },
- workspaces: [{ id: "ws-1", name: "Test WS" }],
- members: [{ user_id: "user-1", name: "Test User", email: "[email protected]" }],
- agents: [{ id: "agent-1", name: "Claude Agent" }],
- }),
- { getState: () => ({
- workspace: { id: "ws-1", name: "Test WS" },
- workspaces: [{ id: "ws-1", name: "Test WS" }],
- members: [{ user_id: "user-1", name: "Test User", email: "[email protected]" }],
- agents: [{ id: "agent-1", name: "Claude Agent" }],
- }),
- },
- ),
- registerWorkspaceStore: vi.fn(),
-}));
-
-// Mock @multica/core/auth (used by @multica/views components)
-vi.mock("@multica/core/auth", () => ({
- useAuthStore: Object.assign(
- (selector: (s: any) => any) =>
- selector({
- user: { id: "user-1", name: "Test User", email: "[email protected]" },
- isLoading: false,
- }),
- { getState: () => ({
- user: { id: "user-1", name: "Test User", email: "[email protected]" },
- isLoading: false,
- }),
- },
- ),
- registerAuthStore: vi.fn(),
- createAuthStore: vi.fn(),
-}));
-
-// Mock @multica/views/navigation (AppLink used by views components)
-vi.mock("@multica/views/navigation", () => ({
- AppLink: ({ children, href, ...props }: any) => <a href={href} {...props}>{children}</a>,
- useNavigation: () => ({ push: vi.fn(), pathname: "/issues/issue-1" }),
- NavigationProvider: ({ children }: { children: React.ReactNode }) => children,
-}));
-
-// Mock @multica/views/editor (ContentEditor, TitleEditor used by IssueDetail)
-vi.mock("@multica/views/editor", () => ({
- ReadonlyContent: ({ content }: { content: string }) => (
- <div data-testid="readonly-content">{content}</div>
- ),
- ContentEditor: forwardRef(({ defaultValue, onUpdate, placeholder, onSubmit }: any, ref: any) => {
- const valueRef = useRef(defaultValue || "");
- const [value, setValue] = useState(defaultValue || "");
- useImperativeHandle(ref, () => ({
- getMarkdown: () => valueRef.current,
- clearContent: () => { valueRef.current = ""; setValue(""); },
- focus: () => {},
- }));
- return (
- <textarea
- value={value}
- onChange={(e) => {
- valueRef.current = e.target.value;
- setValue(e.target.value);
- onUpdate?.(e.target.value);
- }}
- onKeyDown={(e) => {
- if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
- onSubmit?.();
- }
- }}
- placeholder={placeholder}
- data-testid="rich-text-editor"
- />
- );
- }),
- TitleEditor: forwardRef(({ defaultValue, placeholder, onBlur, onChange }: any, ref: any) => {
- const valueRef = useRef(defaultValue || "");
- const [value, setValue] = useState(defaultValue || "");
- useImperativeHandle(ref, () => ({
- getText: () => valueRef.current,
- focus: () => {},
- }));
- return (
- <input
- value={value}
- onChange={(e) => {
- valueRef.current = e.target.value;
- setValue(e.target.value);
- onChange?.(e.target.value);
- }}
- onBlur={() => onBlur?.(valueRef.current)}
- placeholder={placeholder}
- data-testid="title-editor"
- />
- );
- }),
-}));
-
-// Mock @multica/views/workspace/workspace-avatar
-vi.mock("@multica/views/workspace/workspace-avatar", () => ({
- WorkspaceAvatar: ({ name }: { name: string }) => <span>{name.charAt(0)}</span>,
-}));
-
-// Mock @multica/views/common/actor-avatar
-vi.mock("@multica/views/common/actor-avatar", () => ({
- ActorAvatar: ({ actorType, actorId }: any) => <span data-testid="actor-avatar">{actorType}:{actorId}</span>,
-}));
-
-// Mock @multica/views/common/markdown
-vi.mock("@multica/views/common/markdown", () => ({
- Markdown: ({ children }: { children: string }) => <div>{children}</div>,
-}));
-
-// Mock workspace feature
-vi.mock("@/features/workspace", () => ({
- useWorkspaceStore: (selector: (s: any) => any) =>
- selector({
- workspace: { id: "ws-1", name: "Test WS" },
- workspaces: [{ id: "ws-1", name: "Test WS" }],
- members: [{ user_id: "user-1", name: "Test User", email: "[email protected]" }],
- agents: [{ id: "agent-1", name: "Claude Agent" }],
- }),
- useActorName: () => ({
- getMemberName: (id: string) => (id === "user-1" ? "Test User" : "Unknown"),
- getAgentName: (id: string) => (id === "agent-1" ? "Claude Agent" : "Unknown Agent"),
- getActorName: (type: string, id: string) => {
- if (type === "member" && id === "user-1") return "Test User";
- if (type === "agent" && id === "agent-1") return "Claude Agent";
- return "Unknown";
- },
- getActorInitials: (type: string, id: string) => {
- if (type === "member") return "TU";
- if (type === "agent") return "CA";
- return "??";
- },
- getActorAvatarUrl: () => null,
- }),
-}));
-
-vi.mock("@/platform/workspace", () => ({
- useWorkspaceStore: (selector: (s: any) => any) =>
- selector({
- workspace: { id: "ws-1", name: "Test WS" },
- workspaces: [{ id: "ws-1", name: "Test WS" }],
- members: [{ user_id: "user-1", name: "Test User", email: "[email protected]" }],
- agents: [{ id: "agent-1", name: "Claude Agent" }],
- }),
-}));
-
-// Mock workspace hooks from core
-vi.mock("@multica/core/workspace/hooks", () => ({
- useActorName: () => ({
- getMemberName: (id: string) => (id === "user-1" ? "Test User" : "Unknown"),
- getAgentName: (id: string) => (id === "agent-1" ? "Claude Agent" : "Unknown Agent"),
- getActorName: (type: string, id: string) => {
- if (type === "member" && id === "user-1") return "Test User";
- if (type === "agent" && id === "agent-1") return "Claude Agent";
- return "Unknown";
- },
- getActorInitials: (type: string, id: string) => {
- if (type === "member") return "TU";
- if (type === "agent") return "CA";
- return "??";
- },
- getActorAvatarUrl: () => null,
- }),
-}));
-
-// Mock issue store — only client state remains (activeIssueId)
-vi.mock("@/features/issues", () => ({
- useIssueStore: Object.assign(
- (selector: (s: any) => any) => selector({ activeIssueId: null }),
- { getState: () => ({ activeIssueId: null, setActiveIssue: vi.fn() }) },
- ),
-}));
-
-vi.mock("@multica/core/issues", () => ({
- useIssueStore: Object.assign(
- (selector: (s: any) => any) => selector({ activeIssueId: null }),
- { getState: () => ({ activeIssueId: null, setActiveIssue: vi.fn() }) },
- ),
-}));
-
-// Mock ws-context
-vi.mock("@/features/realtime", () => ({
- useWSEvent: () => {},
- useWSReconnect: () => {},
-}));
-
-// Mock core realtime (hooks now import from @multica/core/realtime)
-vi.mock("@multica/core/realtime", () => ({
- useWSEvent: () => {},
- useWSReconnect: () => {},
- useWS: () => ({ subscribe: vi.fn(() => () => {}), onReconnect: vi.fn(() => () => {}) }),
- WSProvider: ({ children }: { children: React.ReactNode }) => children,
- useRealtimeSync: () => {},
-}));
-
-// Mock calendar (react-day-picker needs browser APIs)
-vi.mock("@/components/ui/calendar", () => ({
- Calendar: () => null,
-}));
-
-// Mock ContentEditor (Tiptap needs real DOM)
-vi.mock("@/features/editor", () => ({
- ReadonlyContent: ({ content }: { content: string }) => (
- <div data-testid="readonly-content">{content}</div>
- ),
- ContentEditor: forwardRef(({ defaultValue, onUpdate, placeholder, onSubmit }: any, ref: any) => {
- const valueRef = useRef(defaultValue || "");
- const [value, setValue] = useState(defaultValue || "");
- useImperativeHandle(ref, () => ({
- getMarkdown: () => valueRef.current,
- clearContent: () => { valueRef.current = ""; setValue(""); },
- focus: () => {},
- }));
- return (
- <textarea
- value={value}
- onChange={(e) => {
- valueRef.current = e.target.value;
- setValue(e.target.value);
- onUpdate?.(e.target.value);
- }}
- onKeyDown={(e) => {
- if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
- onSubmit?.();
- }
- }}
- placeholder={placeholder}
- data-testid="rich-text-editor"
- />
- );
- }),
- TitleEditor: forwardRef(({ defaultValue, placeholder, onBlur, onChange }: any, ref: any) => {
- const valueRef = useRef(defaultValue || "");
- const [value, setValue] = useState(defaultValue || "");
- useImperativeHandle(ref, () => ({
- getText: () => valueRef.current,
- focus: () => {},
- }));
- return (
- <input
- value={value}
- onChange={(e) => {
- valueRef.current = e.target.value;
- setValue(e.target.value);
- onChange?.(e.target.value);
- }}
- onBlur={() => onBlur?.(valueRef.current)}
- placeholder={placeholder}
- data-testid="title-editor"
- />
- );
- }),
-}));
-
-// Mock api (core queries/mutations use @multica/core/api, some components use @/platform/api)
-
-const mockApiObj = vi.hoisted(() => ({
- getIssue: vi.fn(),
- listTimeline: vi.fn(),
- listComments: vi.fn().mockResolvedValue([]),
- createComment: vi.fn(),
- updateComment: vi.fn(),
- deleteComment: vi.fn(),
- deleteIssue: vi.fn(),
- updateIssue: vi.fn(),
- listIssueSubscribers: vi.fn().mockResolvedValue([]),
- subscribeToIssue: vi.fn().mockResolvedValue(undefined),
- unsubscribeFromIssue: vi.fn().mockResolvedValue(undefined),
- getActiveTasksForIssue: vi.fn().mockResolvedValue({ tasks: [] }),
- listTasksByIssue: vi.fn().mockResolvedValue([]),
- listTaskMessages: vi.fn().mockResolvedValue([]),
- listChildIssues: vi.fn().mockResolvedValue({ issues: [] }),
- listIssues: vi.fn().mockResolvedValue({ issues: [], total: 0 }),
- uploadFile: vi.fn(),
-}));
-
-vi.mock("@multica/core/api", () => ({
- api: mockApiObj,
- getApi: () => mockApiObj,
- setApiInstance: vi.fn(),
-}));
-
-vi.mock("@/platform/api", () => ({
- api: mockApiObj,
-}));
-
-// Mock issue config from core
-vi.mock("@multica/core/issues/config", () => ({
- ALL_STATUSES: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],
- BOARD_STATUSES: ["backlog", "todo", "in_progress", "in_review", "done", "blocked"],
- STATUS_ORDER: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],
- STATUS_CONFIG: {
- backlog: { label: "Backlog", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
- todo: { label: "Todo", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
- in_progress: { label: "In Progress", iconColor: "text-warning", hoverBg: "hover:bg-warning/10" },
- in_review: { label: "In Review", iconColor: "text-success", hoverBg: "hover:bg-success/10" },
- done: { label: "Done", iconColor: "text-info", hoverBg: "hover:bg-info/10" },
- blocked: { label: "Blocked", iconColor: "text-destructive", hoverBg: "hover:bg-destructive/10" },
- cancelled: { label: "Cancelled", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
- },
- PRIORITY_ORDER: ["urgent", "high", "medium", "low", "none"],
- PRIORITY_CONFIG: {
- urgent: { label: "Urgent", bars: 4, color: "text-destructive" },
- high: { label: "High", bars: 3, color: "text-warning" },
- medium: { label: "Medium", bars: 2, color: "text-warning" },
- low: { label: "Low", bars: 1, color: "text-info" },
- none: { label: "No priority", bars: 0, color: "text-muted-foreground" },
- },
-}));
-
-// Mock modals
-vi.mock("@multica/core/modals", () => ({
- useModalStore: Object.assign(
- () => ({ open: vi.fn() }),
- { getState: () => ({ open: vi.fn() }) },
- ),
-}));
-
-// Mock utils
-vi.mock("@multica/core/utils", () => ({
- timeAgo: (date: string) => "1d ago",
-}));
-
-const mockIssue: Issue = {
- id: "issue-1",
- workspace_id: "ws-1",
- number: 1,
- identifier: "TES-1",
- title: "Implement authentication",
- description: "Add JWT auth to the backend",
- status: "in_progress",
- priority: "high",
- assignee_type: "member",
- assignee_id: "user-1",
- creator_type: "member",
- creator_id: "user-1",
- parent_issue_id: null,
- project_id: null,
- position: 0,
- due_date: "2026-06-01T00:00:00Z",
- created_at: "2026-01-15T00:00:00Z",
- updated_at: "2026-01-20T00:00:00Z",
-};
-
-const mockTimeline: TimelineEntry[] = [
- {
- type: "comment",
- id: "comment-1",
- actor_type: "member",
- actor_id: "user-1",
- content: "Started working on this",
- parent_id: null,
- created_at: "2026-01-16T00:00:00Z",
- updated_at: "2026-01-16T00:00:00Z",
- comment_type: "comment",
- },
- {
- type: "comment",
- id: "comment-2",
- actor_type: "agent",
- actor_id: "agent-1",
- content: "I can help with this",
- parent_id: null,
- created_at: "2026-01-17T00:00:00Z",
- updated_at: "2026-01-17T00:00:00Z",
- comment_type: "comment",
- },
-];
-
-import IssueDetailPage from "./page";
-
-function createTestQueryClient() {
- return new QueryClient({
- defaultOptions: {
- queries: { retry: false, gcTime: 0 },
- mutations: { retry: false },
- },
- });
-}
-
-// React 19 use(Promise) needs the promise to resolve within act + Suspense
-async function renderPage(id = "issue-1") {
- const queryClient = createTestQueryClient();
- let result: ReturnType<typeof render>;
- await act(async () => {
- result = render(
- <QueryClientProvider client={queryClient}>
- <WorkspaceIdProvider wsId="ws-1">
- <Suspense fallback={<div>Suspense loading...</div>}>
- <IssueDetailPage params={Promise.resolve({ id })} />
- </Suspense>
- </WorkspaceIdProvider>
- </QueryClientProvider>,
- );
- });
- return result!;
-}
-
-describe("IssueDetailPage", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("renders issue details after loading", async () => {
- mockApiObj.getIssue.mockResolvedValueOnce(mockIssue);
- mockApiObj.listTimeline.mockResolvedValueOnce(mockTimeline);
- await renderPage();
-
- await waitFor(() => {
- expect(
- screen.getAllByText("Implement authentication").length,
- ).toBeGreaterThanOrEqual(1);
- });
-
- expect(
- screen.getByText("Add JWT auth to the backend"),
- ).toBeInTheDocument();
- });
-
- it("renders issue properties sidebar", async () => {
- mockApiObj.getIssue.mockResolvedValueOnce(mockIssue);
- mockApiObj.listTimeline.mockResolvedValueOnce(mockTimeline);
- await renderPage();
-
- await waitFor(() => {
- expect(screen.getByText("Properties")).toBeInTheDocument();
- });
-
- expect(screen.getByText("In Progress")).toBeInTheDocument();
- expect(screen.getByText("High")).toBeInTheDocument();
- });
-
- it("renders comments", async () => {
- mockApiObj.getIssue.mockResolvedValueOnce(mockIssue);
- mockApiObj.listTimeline.mockResolvedValueOnce(mockTimeline);
- await renderPage();
-
- await waitFor(() => {
- expect(
- screen.getByText("Started working on this"),
- ).toBeInTheDocument();
- });
-
- expect(screen.getByText("I can help with this")).toBeInTheDocument();
- expect(screen.getAllByText("Activity").length).toBeGreaterThanOrEqual(1);
- });
-
- it("shows 'Issue not found' for missing issue", async () => {
- // issue-detail fetches getIssue, useIssueReactions also fetches getIssue
- mockApiObj.getIssue.mockRejectedValue(new Error("Not found"));
- mockApiObj.listTimeline.mockRejectedValue(new Error("Not found"));
- await renderPage("nonexistent-id");
-
- await waitFor(() => {
- expect(screen.getByText("This issue does not exist or has been deleted in this workspace.")).toBeInTheDocument();
- });
- });
-
- it("submits a new comment", async () => {
- mockApiObj.getIssue.mockResolvedValueOnce(mockIssue);
- mockApiObj.listTimeline.mockResolvedValueOnce(mockTimeline);
-
- const newComment: Comment = {
- id: "comment-3",
- issue_id: "issue-1",
- content: "New test comment",
- type: "comment",
- author_type: "member",
- author_id: "user-1",
- parent_id: null,
- reactions: [],
- attachments: [],
- created_at: "2026-01-18T00:00:00Z",
- updated_at: "2026-01-18T00:00:00Z",
- };
- mockApiObj.createComment.mockResolvedValueOnce(newComment);
-
- const user = userEvent.setup();
- await renderPage();
-
- await waitFor(() => {
- expect(
- screen.getByPlaceholderText("Leave a comment..."),
- ).toBeInTheDocument();
- });
-
- const commentInput = screen.getByPlaceholderText("Leave a comment...");
-
- // Use fireEvent to update the textarea value and trigger onUpdate
- await act(async () => {
- fireEvent.change(commentInput, { target: { value: "New test comment" } });
- });
-
- // Find the submit button associated with the "Leave a comment..." input.
- // Multiple ArrowUp buttons exist (one per ReplyInput), so we find the
- // button within the same ReplyInput container as our textarea.
- const allArrowUpBtns = screen.getAllByRole("button").filter(
- (btn) => btn.querySelector(".lucide-arrow-up") !== null,
- );
- // The bottom "Leave a comment..." ReplyInput renders last, so its button is last
- const submitBtn = allArrowUpBtns[allArrowUpBtns.length - 1]!;
- await waitFor(() => {
- expect(submitBtn).not.toBeDisabled();
- });
- await user.click(submitBtn);
-
- await waitFor(() => {
- expect(mockApiObj.createComment).toHaveBeenCalled();
- const [issueId, content] = mockApiObj.createComment.mock.calls[0]!;
- expect(issueId).toBe("issue-1");
- expect(content).toBe("New test comment");
- });
-
- await waitFor(() => {
- expect(screen.getByText("New test comment")).toBeInTheDocument();
- });
- });
-
- it("renders breadcrumb navigation", async () => {
- mockApiObj.getIssue.mockResolvedValueOnce(mockIssue);
- mockApiObj.listTimeline.mockResolvedValueOnce(mockTimeline);
- await renderPage();
-
- await waitFor(() => {
- expect(screen.getByText("Test WS")).toBeInTheDocument();
- });
-
- const wsLink = screen.getByText("Test WS");
- expect(wsLink.closest("a")).toHaveAttribute("href", "/issues");
- });
-});
diff --git a/packages/views/auth/login-page.test.tsx b/packages/views/auth/login-page.test.tsx
new file mode 100644
index 0000000000..263af530f2
--- /dev/null
+++ b/packages/views/auth/login-page.test.tsx
@@ -0,0 +1,665 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { render, screen, waitFor, act } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+
+// jsdom doesn't provide elementFromPoint; input-otp calls it on a timer.
+if (typeof document.elementFromPoint !== "function") {
+ document.elementFromPoint = () => null;
+}
+
+// ---------------------------------------------------------------------------
+// Hoisted mocks
+// ---------------------------------------------------------------------------
+
+const mockSendCode = vi.hoisted(() => vi.fn());
+const mockVerifyCode = vi.hoisted(() => vi.fn());
+const mockHydrateWorkspace = vi.hoisted(() => vi.fn());
+const mockApiListWorkspaces = vi.hoisted(() => vi.fn());
+const mockApiVerifyCode = vi.hoisted(() => vi.fn());
+const mockApiSetToken = vi.hoisted(() => vi.fn());
+const mockApiGetMe = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: Object.assign(
+ // Zustand hook form — component may call useAuthStore(selector)
+ (selector?: (s: unknown) => unknown) => {
+ const state = { sendCode: mockSendCode, verifyCode: mockVerifyCode };
+ return selector ? selector(state) : state;
+ },
+ {
+ getState: () => ({
+ sendCode: mockSendCode,
+ verifyCode: mockVerifyCode,
+ }),
+ },
+ ),
+}));
+
+vi.mock("@multica/core/workspace", () => ({
+ useWorkspaceStore: Object.assign(
+ (selector?: (s: unknown) => unknown) => {
+ const state = { hydrateWorkspace: mockHydrateWorkspace };
+ return selector ? selector(state) : state;
+ },
+ {
+ getState: () => ({
+ hydrateWorkspace: mockHydrateWorkspace,
+ }),
+ },
+ ),
+}));
+
+vi.mock("@multica/core/api", () => ({
+ api: {
+ listWorkspaces: mockApiListWorkspaces,
+ verifyCode: mockApiVerifyCode,
+ setToken: mockApiSetToken,
+ getMe: mockApiGetMe,
+ },
+}));
+
+vi.mock("@multica/core/types", () => ({}));
+
+// ---------------------------------------------------------------------------
+// Import after mocks
+// ---------------------------------------------------------------------------
+
+import { LoginPage, validateCliCallback } from "./login-page";
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function getOTPInput() {
+ // input-otp renders a single hidden <input> that holds the OTP value
+ return screen.getByRole("textbox", { hidden: true });
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+describe("LoginPage", () => {
+ const onSuccess = vi.fn();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Default: no existing session
+ localStorage.clear();
+ // Reset window.location for tests that change it
+ Object.defineProperty(window, "location", {
+ writable: true,
+ value: { href: "http://localhost:3000" },
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // Email step rendering
+ // -------------------------------------------------------------------------
+
+ it("renders email form with 'Sign in to Multica' title", () => {
+ render(<LoginPage onSuccess={onSuccess} />);
+ expect(
+ screen.getByText(/sign in to multica/i),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(/enter your email to get a login code/i),
+ ).toBeInTheDocument();
+ expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /continue/i }),
+ ).toBeInTheDocument();
+ });
+
+ // -------------------------------------------------------------------------
+ // Email validation
+ // -------------------------------------------------------------------------
+
+ it("shows error when submitting with empty email", async () => {
+ render(<LoginPage onSuccess={onSuccess} />);
+
+ // The Continue button is disabled when email is empty, so we submit the
+ // form programmatically the same way the component does — via form submit.
+ // Since the button is disabled, we directly call handleSendCode's logic
+ // by removing the required attr and submitting.
+ const emailInput = screen.getByLabelText(/email/i);
+ // The input has required + the button is disabled, so we need to type
+ // a space then clear to trigger the empty-email error path.
+ // Actually, the component guards `if (!email)` in handleSendCode.
+ // But the button is disabled when `!email`. Let's verify:
+ const button = screen.getByRole("button", { name: /continue/i });
+ expect(button).toBeDisabled();
+
+ // Type an email to enable button, then clear it — button becomes disabled again
+ const user = userEvent.setup();
+ await user.type(emailInput, "a");
+ expect(button).not.toBeDisabled();
+ await user.clear(emailInput);
+ expect(button).toBeDisabled();
+ });
+
+ // -------------------------------------------------------------------------
+ // sendCode flow
+ // -------------------------------------------------------------------------
+
+ it("calls sendCode on form submit with email", async () => {
+ mockSendCode.mockResolvedValueOnce(undefined);
+ render(<LoginPage onSuccess={onSuccess} />);
+
+ const user = userEvent.setup();
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ expect(mockSendCode).toHaveBeenCalledWith("[email protected]");
+ });
+
+ it("shows 'Sending code...' while submitting", async () => {
+ // Never resolve so loading stays true
+ mockSendCode.mockReturnValueOnce(new Promise(() => {}));
+ render(<LoginPage onSuccess={onSuccess} />);
+
+ const user = userEvent.setup();
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ expect(screen.getByText(/sending code/i)).toBeInTheDocument();
+ });
+
+ it("transitions to code step after successful sendCode", async () => {
+ mockSendCode.mockResolvedValueOnce(undefined);
+ render(<LoginPage onSuccess={onSuccess} />);
+
+ const user = userEvent.setup();
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/check your email/i),
+ ).toBeInTheDocument();
+ });
+ expect(screen.getByText(/[email protected]/)).toBeInTheDocument();
+ });
+
+ it("shows error when sendCode fails", async () => {
+ mockSendCode.mockRejectedValueOnce(new Error("Rate limited"));
+ render(<LoginPage onSuccess={onSuccess} />);
+
+ const user = userEvent.setup();
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ await waitFor(() => {
+ expect(screen.getByText("Rate limited")).toBeInTheDocument();
+ });
+ });
+
+ it("shows generic error when sendCode throws non-Error", async () => {
+ mockSendCode.mockRejectedValueOnce("boom");
+ render(<LoginPage onSuccess={onSuccess} />);
+
+ const user = userEvent.setup();
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/failed to send code/i),
+ ).toBeInTheDocument();
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // Code verification
+ // -------------------------------------------------------------------------
+
+ it("calls verifyCode, listWorkspaces, hydrateWorkspace, then onSuccess", async () => {
+ mockSendCode.mockResolvedValueOnce(undefined);
+ mockVerifyCode.mockResolvedValueOnce(undefined);
+ mockApiListWorkspaces.mockResolvedValueOnce([{ id: "ws-1" }]);
+ mockHydrateWorkspace.mockReturnValueOnce({ id: "ws-1" });
+
+ render(<LoginPage onSuccess={onSuccess} />);
+
+ const user = userEvent.setup();
+ // Step 1: email
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ // Step 2: code
+ await waitFor(() => {
+ expect(
+ screen.getByText(/check your email/i),
+ ).toBeInTheDocument();
+ });
+
+ const otpInput = getOTPInput();
+ await user.type(otpInput, "123456");
+
+ await waitFor(() => {
+ expect(mockVerifyCode).toHaveBeenCalledWith(
+ "123456",
+ );
+ expect(mockApiListWorkspaces).toHaveBeenCalled();
+ expect(mockHydrateWorkspace).toHaveBeenCalledWith(
+ [{ id: "ws-1" }],
+ undefined,
+ );
+ expect(onSuccess).toHaveBeenCalled();
+ });
+ });
+
+ it("shows error on invalid code", async () => {
+ mockSendCode.mockResolvedValueOnce(undefined);
+ mockVerifyCode.mockRejectedValueOnce(new Error("Invalid code"));
+
+ render(<LoginPage onSuccess={onSuccess} />);
+
+ const user = userEvent.setup();
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/check your email/i),
+ ).toBeInTheDocument();
+ });
+
+ const otpInput = getOTPInput();
+ await user.type(otpInput, "000000");
+
+ await waitFor(() => {
+ expect(screen.getByText("Invalid code")).toBeInTheDocument();
+ });
+ expect(onSuccess).not.toHaveBeenCalled();
+ });
+
+ // -------------------------------------------------------------------------
+ // Resend code with cooldown
+ // -------------------------------------------------------------------------
+
+ it("disables resend button during cooldown", async () => {
+ mockSendCode.mockResolvedValue(undefined);
+ render(<LoginPage onSuccess={onSuccess} />);
+
+ const user = userEvent.setup();
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/check your email/i),
+ ).toBeInTheDocument();
+ });
+
+ // After transitioning to code step, cooldown is 10s
+ const resendBtn = screen.getByRole("button", { name: /resend in/i });
+ expect(resendBtn).toBeDisabled();
+ });
+
+ it("shows resend button with cooldown text after sending code", async () => {
+ mockSendCode.mockResolvedValue(undefined);
+ const user = userEvent.setup();
+ render(<LoginPage onSuccess={onSuccess} />);
+
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ await waitFor(() => {
+ expect(screen.getByText(/check your email/i)).toBeInTheDocument();
+ });
+
+ // After transition, resend shows cooldown text and is disabled
+ expect(screen.getByText(/resend in/i)).toBeInTheDocument();
+ });
+
+ it("calls sendCode again when resend is clicked after cooldown", async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+
+ mockSendCode.mockResolvedValue(undefined);
+ render(<LoginPage onSuccess={onSuccess} />);
+
+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ await waitFor(() => {
+ expect(screen.getByText(/check your email/i)).toBeInTheDocument();
+ });
+
+ // sendCode was called once for the initial send
+ expect(mockSendCode).toHaveBeenCalledTimes(1);
+
+ // Advance past the 10s cooldown one second at a time so React can
+ // process each setCooldown state update between ticks.
+ for (let i = 0; i < 11; i++) {
+ await act(async () => {
+ vi.advanceTimersByTime(1_000);
+ });
+ }
+
+ await waitFor(() => {
+ expect(screen.getByText(/resend code/i)).toBeInTheDocument();
+ });
+
+ const resendBtn = screen.getByRole("button", { name: /resend code/i });
+ expect(resendBtn).not.toBeDisabled();
+
+ await user.click(resendBtn);
+ expect(mockSendCode).toHaveBeenCalledTimes(2);
+
+ vi.useRealTimers();
+ });
+
+ // -------------------------------------------------------------------------
+ // Google OAuth
+ // -------------------------------------------------------------------------
+
+ it("renders Google OAuth button when google prop provided", () => {
+ render(
+ <LoginPage
+ onSuccess={onSuccess}
+ google={{ clientId: "goog-123", redirectUri: "http://localhost/cb" }}
+ />,
+ );
+ expect(
+ screen.getByRole("button", { name: /continue with google/i }),
+ ).toBeInTheDocument();
+ });
+
+ it("hides Google OAuth button when google prop omitted", () => {
+ render(<LoginPage onSuccess={onSuccess} />);
+ expect(
+ screen.queryByRole("button", { name: /continue with google/i }),
+ ).not.toBeInTheDocument();
+ });
+
+ // -------------------------------------------------------------------------
+ // CLI callback — existing session
+ // -------------------------------------------------------------------------
+
+ it("shows cli_confirm step when existing session + cliCallback", async () => {
+ localStorage.setItem("multica_token", "existing-jwt");
+ mockApiGetMe.mockResolvedValueOnce({
+ id: "u-1",
+ email: "[email protected]",
+ name: "Test User",
+ });
+
+ render(
+ <LoginPage
+ onSuccess={onSuccess}
+ cliCallback={{ url: "http://localhost:9876/callback", state: "abc" }}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/authorize cli/i),
+ ).toBeInTheDocument();
+ });
+ expect(screen.getByText(/[email protected]/)).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /authorize/i }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /use a different account/i }),
+ ).toBeInTheDocument();
+ });
+
+ it("CLI authorize button redirects to callback URL", async () => {
+ localStorage.setItem("multica_token", "existing-jwt");
+ mockApiGetMe.mockResolvedValueOnce({
+ id: "u-1",
+ email: "[email protected]",
+ name: "Test User",
+ });
+ const onTokenObtained = vi.fn();
+
+ render(
+ <LoginPage
+ onSuccess={onSuccess}
+ onTokenObtained={onTokenObtained}
+ cliCallback={{ url: "http://localhost:9876/callback", state: "abc" }}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/authorize cli/i),
+ ).toBeInTheDocument();
+ });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("button", { name: /^authorize$/i }));
+
+ expect(onTokenObtained).toHaveBeenCalled();
+ expect(window.location.href).toContain(
+ "http://localhost:9876/callback?token=existing-jwt&state=abc",
+ );
+ });
+
+ it("'Use a different account' returns to email step", async () => {
+ localStorage.setItem("multica_token", "existing-jwt");
+ mockApiGetMe.mockResolvedValueOnce({
+ id: "u-1",
+ email: "[email protected]",
+ name: "Test User",
+ });
+
+ render(
+ <LoginPage
+ onSuccess={onSuccess}
+ cliCallback={{ url: "http://localhost:9876/callback", state: "abc" }}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/authorize cli/i),
+ ).toBeInTheDocument();
+ });
+
+ const user = userEvent.setup();
+ await user.click(
+ screen.getByRole("button", { name: /use a different account/i }),
+ );
+
+ expect(
+ screen.getByText(/sign in to multica/i),
+ ).toBeInTheDocument();
+ });
+
+ // -------------------------------------------------------------------------
+ // CLI callback — code verification redirects
+ // -------------------------------------------------------------------------
+
+ it("CLI code verification redirects to callback URL", async () => {
+ mockSendCode.mockResolvedValueOnce(undefined);
+ mockApiVerifyCode.mockResolvedValueOnce({ token: "new-jwt-token" });
+ const onTokenObtained = vi.fn();
+
+ render(
+ <LoginPage
+ onSuccess={onSuccess}
+ onTokenObtained={onTokenObtained}
+ cliCallback={{ url: "http://localhost:9876/callback", state: "xyz" }}
+ />,
+ );
+
+ const user = userEvent.setup();
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/check your email/i),
+ ).toBeInTheDocument();
+ });
+
+ const otpInput = getOTPInput();
+ await user.type(otpInput, "654321");
+
+ await waitFor(() => {
+ expect(mockApiVerifyCode).toHaveBeenCalledWith(
+ "654321",
+ );
+ expect(onTokenObtained).toHaveBeenCalled();
+ expect(window.location.href).toContain(
+ "http://localhost:9876/callback?token=new-jwt-token&state=xyz",
+ );
+ });
+
+ // Normal verifyCode should NOT be called in CLI path
+ expect(mockVerifyCode).not.toHaveBeenCalled();
+ // onSuccess should NOT be called in CLI path — redirect handles it
+ expect(onSuccess).not.toHaveBeenCalled();
+ });
+
+ // -------------------------------------------------------------------------
+ // Logo prop
+ // -------------------------------------------------------------------------
+
+ it("renders logo when provided", () => {
+ render(
+ <LoginPage
+ onSuccess={onSuccess}
+ logo={<div data-testid="custom-logo">Logo</div>}
+ />,
+ );
+ expect(screen.getByTestId("custom-logo")).toBeInTheDocument();
+ });
+
+ it("does not render logo placeholder when omitted", () => {
+ render(<LoginPage onSuccess={onSuccess} />);
+ expect(screen.queryByTestId("custom-logo")).not.toBeInTheDocument();
+ });
+
+ // -------------------------------------------------------------------------
+ // onTokenObtained callback
+ // -------------------------------------------------------------------------
+
+ it("calls onTokenObtained after successful verification", async () => {
+ mockSendCode.mockResolvedValueOnce(undefined);
+ mockVerifyCode.mockResolvedValueOnce(undefined);
+ mockApiListWorkspaces.mockResolvedValueOnce([{ id: "ws-1" }]);
+ mockHydrateWorkspace.mockReturnValueOnce({ id: "ws-1" });
+ const onTokenObtained = vi.fn();
+
+ render(
+ <LoginPage
+ onSuccess={onSuccess}
+ onTokenObtained={onTokenObtained}
+ />,
+ );
+
+ const user = userEvent.setup();
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/check your email/i),
+ ).toBeInTheDocument();
+ });
+
+ const otpInput = getOTPInput();
+ await user.type(otpInput, "123456");
+
+ await waitFor(() => {
+ expect(onTokenObtained).toHaveBeenCalled();
+ expect(onSuccess).toHaveBeenCalled();
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // Back button on code step
+ // -------------------------------------------------------------------------
+
+ it("back button returns to email step", async () => {
+ mockSendCode.mockResolvedValueOnce(undefined);
+ render(<LoginPage onSuccess={onSuccess} />);
+
+ const user = userEvent.setup();
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/check your email/i),
+ ).toBeInTheDocument();
+ });
+
+ await user.click(screen.getByRole("button", { name: /back/i }));
+
+ expect(
+ screen.getByText(/sign in to multica/i),
+ ).toBeInTheDocument();
+ });
+
+ // -------------------------------------------------------------------------
+ // lastWorkspaceId
+ // -------------------------------------------------------------------------
+
+ it("passes lastWorkspaceId to hydrateWorkspace", async () => {
+ mockSendCode.mockResolvedValueOnce(undefined);
+ mockVerifyCode.mockResolvedValueOnce(undefined);
+ mockApiListWorkspaces.mockResolvedValueOnce([
+ { id: "ws-1" },
+ { id: "ws-2" },
+ ]);
+ mockHydrateWorkspace.mockReturnValueOnce({ id: "ws-2" });
+
+ render(
+ <LoginPage onSuccess={onSuccess} lastWorkspaceId="ws-2" />,
+ );
+
+ const user = userEvent.setup();
+ await user.type(screen.getByLabelText(/email/i), "[email protected]");
+ await user.click(screen.getByRole("button", { name: /continue/i }));
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/check your email/i),
+ ).toBeInTheDocument();
+ });
+
+ const otpInput = getOTPInput();
+ await user.type(otpInput, "123456");
+
+ await waitFor(() => {
+ expect(mockHydrateWorkspace).toHaveBeenCalledWith(
+ [{ id: "ws-1" }, { id: "ws-2" }],
+ "ws-2",
+ );
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// validateCliCallback (exported helper)
+// ---------------------------------------------------------------------------
+
+describe("validateCliCallback", () => {
+ it("accepts http://localhost", () => {
+ expect(validateCliCallback("http://localhost:9876/callback")).toBe(true);
+ });
+
+ it("accepts http://127.0.0.1", () => {
+ expect(validateCliCallback("http://127.0.0.1:8080/cb")).toBe(true);
+ });
+
+ it("rejects https:// URLs", () => {
+ expect(validateCliCallback("https://localhost:9876/callback")).toBe(false);
+ });
+
+ it("rejects non-localhost hosts", () => {
+ expect(validateCliCallback("http://evil.com:9876/callback")).toBe(false);
+ });
+
+ it("rejects invalid URLs", () => {
+ expect(validateCliCallback("not-a-url")).toBe(false);
+ });
+});
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
new file mode 100644
index 0000000000..c99957bbeb
--- /dev/null
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -0,0 +1,453 @@
+import { forwardRef, useRef, useState, useImperativeHandle } from "react";
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { Issue, TimelineEntry } from "@multica/core/types";
+import { WorkspaceIdProvider } from "@multica/core/hooks";
+
+// ---------------------------------------------------------------------------
+// Mocks
+// ---------------------------------------------------------------------------
+
+// Mock @multica/core/auth
+const mockAuthUser = { id: "user-1", email: "[email protected]", name: "Test User" };
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: Object.assign(
+ (selector?: any) => {
+ const state = { user: mockAuthUser, isAuthenticated: true };
+ return selector ? selector(state) : state;
+ },
+ { getState: () => ({ user: mockAuthUser, isAuthenticated: true }) },
+ ),
+ registerAuthStore: vi.fn(),
+ createAuthStore: vi.fn(),
+}));
+
+// Mock @multica/core/workspace
+vi.mock("@multica/core/workspace", () => ({
+ useWorkspaceStore: Object.assign(
+ (selector?: any) => {
+ const state = {
+ workspace: { id: "ws-1", name: "Test WS", slug: "test" },
+ agents: [],
+ members: [],
+ };
+ return selector ? selector(state) : state;
+ },
+ {
+ getState: () => ({
+ workspace: { id: "ws-1", name: "Test WS", slug: "test" },
+ agents: [],
+ members: [],
+ }),
+ },
+ ),
+ registerWorkspaceStore: vi.fn(),
+}));
+
+// Mock @multica/core/workspace/hooks
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({
+ getMemberName: (id: string) => (id === "user-1" ? "Test User" : "Unknown"),
+ getAgentName: (id: string) => (id === "agent-1" ? "Claude Agent" : "Unknown Agent"),
+ getActorName: (type: string, id: string) => {
+ if (type === "member" && id === "user-1") return "Test User";
+ if (type === "agent" && id === "agent-1") return "Claude Agent";
+ return "Unknown";
+ },
+ getActorInitials: (type: string) => (type === "member" ? "TU" : "CA"),
+ getActorAvatarUrl: () => null,
+ }),
+}));
+
+// Mock workspace queries
+vi.mock("@multica/core/workspace/queries", () => ({
+ memberListOptions: () => ({
+ queryKey: ["workspaces", "ws-1", "members"],
+ queryFn: () => Promise.resolve([{ user_id: "user-1", name: "Test User", email: "[email protected]", role: "admin" }]),
+ }),
+ agentListOptions: () => ({
+ queryKey: ["workspaces", "ws-1", "agents"],
+ queryFn: () => Promise.resolve([]),
+ }),
+}));
+
+// Mock navigation
+vi.mock("../../navigation", () => ({
+ AppLink: ({ children, href, ...props }: any) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+ useNavigation: () => ({ push: vi.fn(), pathname: "/issues/issue-1", getShareableUrl: undefined }),
+ NavigationProvider: ({ children }: { children: React.ReactNode }) => children,
+}));
+
+// Mock editor components (Tiptap requires real DOM)
+vi.mock("../../editor", () => ({
+ ReadonlyContent: ({ content }: { content: string }) => (
+ <div data-testid="readonly-content">{content}</div>
+ ),
+ ContentEditor: forwardRef(({ defaultValue, onUpdate, placeholder }: any, ref: any) => {
+ const valueRef = useRef(defaultValue || "");
+ const [value, setValue] = useState(defaultValue || "");
+ useImperativeHandle(ref, () => ({
+ getMarkdown: () => valueRef.current,
+ clearContent: () => { valueRef.current = ""; setValue(""); },
+ focus: () => {},
+ uploadFile: () => {},
+ }));
+ return (
+ <textarea
+ value={value}
+ onChange={(e) => {
+ valueRef.current = e.target.value;
+ setValue(e.target.value);
+ onUpdate?.(e.target.value);
+ }}
+ placeholder={placeholder}
+ data-testid="rich-text-editor"
+ />
+ );
+ }),
+ TitleEditor: forwardRef(({ defaultValue, placeholder, onBlur, onChange }: any, ref: any) => {
+ const valueRef = useRef(defaultValue || "");
+ const [value, setValue] = useState(defaultValue || "");
+ useImperativeHandle(ref, () => ({
+ getText: () => valueRef.current,
+ focus: () => {},
+ }));
+ return (
+ <input
+ value={value}
+ onChange={(e) => {
+ valueRef.current = e.target.value;
+ setValue(e.target.value);
+ onChange?.(e.target.value);
+ }}
+ onBlur={() => onBlur?.(valueRef.current)}
+ placeholder={placeholder}
+ data-testid="title-editor"
+ />
+ );
+ }),
+}));
+
+// Mock common components
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: ({ actorType, actorId }: any) => (
+ <span data-testid="actor-avatar">
+ {actorType}:{actorId}
+ </span>
+ ),
+}));
+
+vi.mock("../../projects/components/project-picker", () => ({
+ ProjectPicker: () => <span data-testid="project-picker">Project</span>,
+}));
+
+// Mock api
+const mockApiObj = vi.hoisted(() => ({
+ getIssue: vi.fn(),
+ listTimeline: vi.fn().mockResolvedValue([]),
+ listComments: vi.fn().mockResolvedValue([]),
+ createComment: vi.fn(),
+ updateComment: vi.fn(),
+ deleteComment: vi.fn(),
+ deleteIssue: vi.fn(),
+ updateIssue: vi.fn(),
+ listIssueSubscribers: vi.fn().mockResolvedValue([]),
+ subscribeToIssue: vi.fn().mockResolvedValue(undefined),
+ unsubscribeFromIssue: vi.fn().mockResolvedValue(undefined),
+ getActiveTasksForIssue: vi.fn().mockResolvedValue({ tasks: [] }),
+ listTasksByIssue: vi.fn().mockResolvedValue([]),
+ listTaskMessages: vi.fn().mockResolvedValue([]),
+ listChildIssues: vi.fn().mockResolvedValue({ issues: [] }),
+ listIssues: vi.fn().mockResolvedValue({ issues: [], total: 0 }),
+ uploadFile: vi.fn(),
+ listIssueReactions: vi.fn().mockResolvedValue([]),
+ addIssueReaction: vi.fn(),
+ removeIssueReaction: vi.fn(),
+ addCommentReaction: vi.fn(),
+ removeCommentReaction: vi.fn(),
+ listMembers: vi.fn().mockResolvedValue([{ user_id: "user-1", name: "Test User", email: "[email protected]", role: "admin" }]),
+ listAgents: vi.fn().mockResolvedValue([]),
+}));
+
+vi.mock("@multica/core/api", () => ({
+ api: mockApiObj,
+ getApi: () => mockApiObj,
+ setApiInstance: vi.fn(),
+}));
+
+// Mock issue config
+vi.mock("@multica/core/issues/config", () => ({
+ ALL_STATUSES: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],
+ BOARD_STATUSES: ["backlog", "todo", "in_progress", "in_review", "done", "blocked"],
+ STATUS_ORDER: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],
+ STATUS_CONFIG: {
+ backlog: { label: "Backlog", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
+ todo: { label: "Todo", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
+ in_progress: { label: "In Progress", iconColor: "text-warning", hoverBg: "hover:bg-warning/10" },
+ in_review: { label: "In Review", iconColor: "text-success", hoverBg: "hover:bg-success/10" },
+ done: { label: "Done", iconColor: "text-info", hoverBg: "hover:bg-info/10" },
+ blocked: { label: "Blocked", iconColor: "text-destructive", hoverBg: "hover:bg-destructive/10" },
+ cancelled: { label: "Cancelled", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
+ },
+ PRIORITY_ORDER: ["urgent", "high", "medium", "low", "none"],
+ PRIORITY_CONFIG: {
+ urgent: { label: "Urgent", bars: 4, color: "text-destructive", badgeBg: "bg-destructive/10", badgeText: "text-destructive" },
+ high: { label: "High", bars: 3, color: "text-warning", badgeBg: "bg-warning/10", badgeText: "text-warning" },
+ medium: { label: "Medium", bars: 2, color: "text-warning", badgeBg: "bg-warning/10", badgeText: "text-warning" },
+ low: { label: "Low", bars: 1, color: "text-info", badgeBg: "bg-info/10", badgeText: "text-info" },
+ none: { label: "No priority", bars: 0, color: "text-muted-foreground", badgeBg: "bg-muted", badgeText: "text-muted-foreground" },
+ },
+}));
+
+// Mock modals
+vi.mock("@multica/core/modals", () => ({
+ useModalStore: Object.assign(
+ () => ({ open: vi.fn() }),
+ { getState: () => ({ open: vi.fn() }) },
+ ),
+}));
+
+// Mock core/utils
+vi.mock("@multica/core/utils", () => ({
+ timeAgo: () => "1d ago",
+}));
+
+// Mock core/hooks/use-file-upload
+vi.mock("@multica/core/hooks/use-file-upload", () => ({
+ useFileUpload: () => ({ uploadWithToast: vi.fn().mockResolvedValue("https://example.com/file.png") }),
+}));
+
+// Mock realtime
+vi.mock("@multica/core/realtime", () => ({
+ useWSEvent: vi.fn(),
+ useWSReconnect: vi.fn(),
+ useWS: () => ({ subscribe: vi.fn(() => () => {}), onReconnect: vi.fn(() => () => {}) }),
+ WSProvider: ({ children }: { children: React.ReactNode }) => children,
+ useRealtimeSync: () => {},
+}));
+
+// Mock sonner
+vi.mock("sonner", () => ({
+ toast: { error: vi.fn(), success: vi.fn() },
+}));
+
+// Mock react-resizable-panels (used by @multica/ui/components/ui/resizable)
+vi.mock("react-resizable-panels", () => ({
+ Group: ({ children, ...props }: any) => <div data-testid="panel-group" {...props}>{children}</div>,
+ Panel: ({ children, ...props }: any) => <div data-testid="panel" {...props}>{children}</div>,
+ Separator: ({ children, ...props }: any) => <div data-testid="panel-handle" {...props}>{children}</div>,
+ useDefaultLayout: () => ({ defaultLayout: undefined, onLayoutChanged: vi.fn() }),
+ usePanelRef: () => ({ current: { isCollapsed: () => false, expand: vi.fn(), collapse: vi.fn() } }),
+}));
+
+// ---------------------------------------------------------------------------
+// Test data
+// ---------------------------------------------------------------------------
+
+const mockIssue: Issue = {
+ id: "issue-1",
+ workspace_id: "ws-1",
+ number: 1,
+ identifier: "TES-1",
+ title: "Implement authentication",
+ description: "Add JWT auth to the backend",
+ status: "in_progress",
+ priority: "high",
+ assignee_type: "member",
+ assignee_id: "user-1",
+ creator_type: "member",
+ creator_id: "user-1",
+ parent_issue_id: null,
+ project_id: null,
+ position: 0,
+ due_date: "2026-06-01T00:00:00Z",
+ created_at: "2026-01-15T00:00:00Z",
+ updated_at: "2026-01-20T00:00:00Z",
+};
+
+const mockTimeline: TimelineEntry[] = [
+ {
+ type: "comment",
+ id: "comment-1",
+ actor_type: "member",
+ actor_id: "user-1",
+ content: "Started working on this",
+ parent_id: null,
+ created_at: "2026-01-16T00:00:00Z",
+ updated_at: "2026-01-16T00:00:00Z",
+ comment_type: "comment",
+ },
+ {
+ type: "comment",
+ id: "comment-2",
+ actor_type: "agent",
+ actor_id: "agent-1",
+ content: "I can help with this",
+ parent_id: null,
+ created_at: "2026-01-17T00:00:00Z",
+ updated_at: "2026-01-17T00:00:00Z",
+ comment_type: "comment",
+ },
+];
+
+// ---------------------------------------------------------------------------
+// Import component under test (after mocks)
+// ---------------------------------------------------------------------------
+
+import { IssueDetail } from "./issue-detail";
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function createTestQueryClient() {
+ return new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, gcTime: 0 },
+ mutations: { retry: false },
+ },
+ });
+}
+
+function renderIssueDetail(issueId = "issue-1") {
+ const queryClient = createTestQueryClient();
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <WorkspaceIdProvider wsId="ws-1">
+ <IssueDetail issueId={issueId} />
+ </WorkspaceIdProvider>
+ </QueryClientProvider>,
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+describe("IssueDetail (shared)", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Default: issue loads successfully
+ mockApiObj.getIssue.mockResolvedValue(mockIssue);
+ mockApiObj.listTimeline.mockResolvedValue(mockTimeline);
+ mockApiObj.listIssueReactions.mockResolvedValue([]);
+ mockApiObj.listIssueSubscribers.mockResolvedValue([]);
+ mockApiObj.listChildIssues.mockResolvedValue({ issues: [] });
+ mockApiObj.listIssues.mockResolvedValue({ issues: [], total: 0 });
+ mockApiObj.getActiveTasksForIssue.mockResolvedValue({ tasks: [] });
+ mockApiObj.listTasksByIssue.mockResolvedValue([]);
+ mockApiObj.listMembers.mockResolvedValue([
+ { user_id: "user-1", name: "Test User", email: "[email protected]", role: "admin" },
+ ]);
+ mockApiObj.listAgents.mockResolvedValue([]);
+ });
+
+ it("shows loading skeleton while data is loading", () => {
+ // Make the API hang to keep loading state
+ mockApiObj.getIssue.mockReturnValue(new Promise(() => {}));
+ renderIssueDetail();
+
+ expect(
+ screen.getAllByRole("generic").some((el) => el.getAttribute("data-slot") === "skeleton"),
+ ).toBe(true);
+ });
+
+ it("renders issue title and description after loading", async () => {
+ renderIssueDetail();
+
+ await waitFor(() => {
+ expect(screen.getByDisplayValue("Implement authentication")).toBeInTheDocument();
+ });
+
+ expect(screen.getByDisplayValue("Add JWT auth to the backend")).toBeInTheDocument();
+ });
+
+ it("renders issue identifier in the breadcrumb", async () => {
+ renderIssueDetail();
+
+ await waitFor(() => {
+ expect(screen.getByText("TES-1")).toBeInTheDocument();
+ });
+ });
+
+ it("renders workspace name as breadcrumb link", async () => {
+ renderIssueDetail();
+
+ await waitFor(() => {
+ expect(screen.getByText("Test WS")).toBeInTheDocument();
+ });
+
+ const wsLink = screen.getByText("Test WS");
+ expect(wsLink.closest("a")).toHaveAttribute("href", "/issues");
+ });
+
+ it("renders properties sidebar with status, priority, assignee, due date", async () => {
+ renderIssueDetail();
+
+ await waitFor(() => {
+ expect(screen.getByText("Properties")).toBeInTheDocument();
+ });
+
+ expect(screen.getByText("Status")).toBeInTheDocument();
+ expect(screen.getByText("Priority")).toBeInTheDocument();
+ expect(screen.getByText("Assignee")).toBeInTheDocument();
+ expect(screen.getByText("Due date")).toBeInTheDocument();
+ });
+
+ it("renders Details section with Created by and dates", async () => {
+ renderIssueDetail();
+
+ await waitFor(() => {
+ expect(screen.getByText("Details")).toBeInTheDocument();
+ });
+
+ expect(screen.getByText("Created by")).toBeInTheDocument();
+ expect(screen.getByText("Created")).toBeInTheDocument();
+ expect(screen.getByText("Updated")).toBeInTheDocument();
+ });
+
+ it("shows 'not found' message when issue does not exist", async () => {
+ mockApiObj.getIssue.mockRejectedValue(new Error("Not found"));
+
+ renderIssueDetail("nonexistent-id");
+
+ await waitFor(() => {
+ expect(
+ screen.getByText("This issue does not exist or has been deleted in this workspace."),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it("shows 'Back to Issues' button when issue is not found and no onDelete prop", async () => {
+ mockApiObj.getIssue.mockRejectedValue(new Error("Not found"));
+
+ renderIssueDetail("nonexistent-id");
+
+ await waitFor(() => {
+ expect(screen.getByText("Back to Issues")).toBeInTheDocument();
+ });
+ });
+
+ it("renders Activity section header", async () => {
+ renderIssueDetail();
+
+ await waitFor(() => {
+ expect(screen.getAllByText("Activity").length).toBeGreaterThanOrEqual(1);
+ });
+ });
+
+ it("renders comments from timeline", async () => {
+ renderIssueDetail();
+
+ await waitFor(() => {
+ expect(screen.getByText("Started working on this")).toBeInTheDocument();
+ });
+
+ expect(screen.getByText("I can help with this")).toBeInTheDocument();
+ });
+});
diff --git a/apps/web/app/(dashboard)/issues/page.test.tsx b/packages/views/issues/components/issues-page.test.tsx
similarity index 62%
rename from apps/web/app/(dashboard)/issues/page.test.tsx
rename to packages/views/issues/components/issues-page.test.tsx
index 14f0232866..1f97aa7697 100644
--- a/apps/web/app/(dashboard)/issues/page.test.tsx
+++ b/packages/views/issues/components/issues-page.test.tsx
@@ -1,54 +1,14 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Issue } from "@multica/core/types";
import { WorkspaceIdProvider } from "@multica/core/hooks";
-// Mock next/navigation
-vi.mock("next/navigation", () => ({
- useRouter: () => ({ push: vi.fn() }),
- usePathname: () => "/issues",
-}));
-
-// Mock next/link
-vi.mock("next/link", () => ({
- default: ({
- children,
- href,
- ...props
- }: {
- children: React.ReactNode;
- href: string;
- [key: string]: any;
- }) => (
- <a href={href} {...props}>
- {children}
- </a>
- ),
-}));
-
-// Mock workspace feature
-vi.mock("@/features/workspace", () => ({
- useActorName: () => ({
- getMemberName: (id: string) => (id === "user-1" ? "Test User" : "Unknown"),
- getAgentName: (id: string) => (id === "agent-1" ? "Claude Agent" : "Unknown Agent"),
- getActorName: (type: string, id: string) =>
- type === "member" ? "Test User" : "Claude Agent",
- getActorInitials: () => "TU",
- getActorAvatarUrl: () => null,
- }),
- useWorkspaceStore: Object.assign(
- (selector?: any) => {
- const state = { workspace: { id: "ws-1", name: "Test", slug: "test" }, agents: [], members: [] };
- return selector ? selector(state) : state;
- },
- { getState: () => ({ workspace: { id: "ws-1", name: "Test", slug: "test" }, agents: [], members: [] }) },
- ),
- WorkspaceAvatar: ({ name }: { name: string }) => <span>{name.charAt(0)}</span>,
-}));
+// ---------------------------------------------------------------------------
+// Mocks
+// ---------------------------------------------------------------------------
-// Mock @multica/core/auth (used by @multica/views pickers like AssigneePicker)
+// Mock @multica/core/auth
const mockAuthUser = { id: "user-1", email: "[email protected]", name: "Test User" };
vi.mock("@multica/core/auth", () => ({
useAuthStore: Object.assign(
@@ -62,95 +22,84 @@ vi.mock("@multica/core/auth", () => ({
createAuthStore: vi.fn(),
}));
-// Mock @multica/core/workspace (used by @multica/views components)
+// Mock @multica/core/workspace
vi.mock("@multica/core/workspace", () => ({
useWorkspaceStore: Object.assign(
(selector?: any) => {
- const state = { workspace: { id: "ws-1", name: "Test", slug: "test" }, agents: [], members: [] };
+ const state = {
+ workspace: { id: "ws-1", name: "Test WS", slug: "test" },
+ agents: [],
+ members: [],
+ };
return selector ? selector(state) : state;
},
- { getState: () => ({ workspace: { id: "ws-1", name: "Test", slug: "test" }, agents: [], members: [] }) },
+ {
+ getState: () => ({
+ workspace: { id: "ws-1", name: "Test WS", slug: "test" },
+ agents: [],
+ members: [],
+ }),
+ },
),
registerWorkspaceStore: vi.fn(),
}));
-vi.mock("@/platform/workspace", () => ({
- useWorkspaceStore: Object.assign(
- (selector?: any) => {
- const state = { workspace: { id: "ws-1", name: "Test", slug: "test" }, agents: [], members: [] };
- return selector ? selector(state) : state;
- },
- { getState: () => ({ workspace: { id: "ws-1", name: "Test", slug: "test" }, agents: [], members: [] }) },
+// Mock @multica/views/navigation (AppLink + useNavigation)
+vi.mock("../../navigation", () => ({
+ AppLink: ({ children, href, ...props }: any) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
),
-}));
-
-// Mock @multica/views/navigation (AppLink used by views components)
-vi.mock("@multica/views/navigation", () => ({
- AppLink: ({ children, href, ...props }: any) => <a href={href} {...props}>{children}</a>,
useNavigation: () => ({ push: vi.fn(), pathname: "/issues" }),
NavigationProvider: ({ children }: { children: React.ReactNode }) => children,
}));
-// Mock @multica/views/workspace/workspace-avatar
-vi.mock("@multica/views/workspace/workspace-avatar", () => ({
- WorkspaceAvatar: ({ name }: { name: string }) => <span>{name.charAt(0)}</span>,
-}));
-
-// Mock WebSocket context
-vi.mock("@/features/realtime", () => ({
- useWSEvent: vi.fn(),
- useWSReconnect: vi.fn(),
- useWS: () => ({ subscribe: vi.fn(() => () => {}), onReconnect: vi.fn(() => () => {}) }),
- WSProvider: ({ children }: { children: React.ReactNode }) => children,
-}));
-
-// Mock sonner toast
-vi.mock("sonner", () => ({
- toast: { error: vi.fn(), success: vi.fn() },
+// Mock workspace avatar
+vi.mock("../../workspace/workspace-avatar", () => ({
+ WorkspaceAvatar: ({ name }: { name: string }) => <span data-testid="workspace-avatar">{name.charAt(0)}</span>,
}));
-// Mock api (core queries/mutations use @multica/core/api)
-const mockUpdateIssue = vi.fn();
+// Mock api (queries use api internally)
const mockListIssues = vi.hoisted(() => vi.fn().mockResolvedValue({ issues: [], total: 0 }));
-
vi.mock("@multica/core/api", () => ({
api: {
listIssues: (...args: any[]) => mockListIssues(...args),
- updateIssue: (...args: any[]) => mockUpdateIssue(...args),
+ updateIssue: vi.fn(),
listMembers: () => Promise.resolve([]),
listAgents: () => Promise.resolve([]),
},
getApi: () => ({
listIssues: (...args: any[]) => mockListIssues(...args),
- updateIssue: (...args: any[]) => mockUpdateIssue(...args),
+ updateIssue: vi.fn(),
listMembers: () => Promise.resolve([]),
listAgents: () => Promise.resolve([]),
}),
setApiInstance: vi.fn(),
}));
-// Mock issue store — only client state remains
-const mockIssueClientState = { activeIssueId: null, setActiveIssue: vi.fn() };
-vi.mock("@multica/core/issues", () => ({
- useIssueStore: Object.assign(
- (selector?: any) => (selector ? selector(mockIssueClientState) : mockIssueClientState),
- { getState: () => mockIssueClientState },
- ),
-}));
-
-vi.mock("@/features/issues", () => ({
- useIssueStore: Object.assign(
- (selector?: any) => (selector ? selector(mockIssueClientState) : mockIssueClientState),
- { getState: () => mockIssueClientState },
- ),
- StatusIcon: () => null,
- PriorityIcon: () => null,
- StatusPicker: ({ value, onChange }: any) => (
- <button onClick={() => onChange?.("todo")}>{value || "todo"}</button>
- ),
- PriorityPicker: ({ value, onChange }: any) => (
- <button onClick={() => onChange?.("none")}>{value || "none"}</button>
- ),
+// Mock issue config
+vi.mock("@multica/core/issues/config", () => ({
+ ALL_STATUSES: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],
+ BOARD_STATUSES: ["backlog", "todo", "in_progress", "in_review", "done", "blocked"],
+ STATUS_ORDER: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],
+ STATUS_CONFIG: {
+ backlog: { label: "Backlog", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
+ todo: { label: "Todo", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
+ in_progress: { label: "In Progress", iconColor: "text-warning", hoverBg: "hover:bg-warning/10" },
+ in_review: { label: "In Review", iconColor: "text-success", hoverBg: "hover:bg-success/10" },
+ done: { label: "Done", iconColor: "text-info", hoverBg: "hover:bg-info/10" },
+ blocked: { label: "Blocked", iconColor: "text-destructive", hoverBg: "hover:bg-destructive/10" },
+ cancelled: { label: "Cancelled", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
+ },
+ PRIORITY_ORDER: ["urgent", "high", "medium", "low", "none"],
+ PRIORITY_CONFIG: {
+ urgent: { label: "Urgent", bars: 4, color: "text-destructive" },
+ high: { label: "High", bars: 3, color: "text-warning" },
+ medium: { label: "Medium", bars: 2, color: "text-warning" },
+ low: { label: "Low", bars: 1, color: "text-info" },
+ none: { label: "No priority", bars: 0, color: "text-muted-foreground" },
+ },
}));
// Mock view store
@@ -206,14 +155,12 @@ vi.mock("@multica/core/issues/stores/view-store", () => ({
],
}));
-// Mock view store context (shared components read from context)
vi.mock("@multica/core/issues/stores/view-store-context", () => ({
ViewStoreProvider: ({ children }: { children: React.ReactNode }) => children,
useViewStore: (selector?: any) => (selector ? selector(mockViewState) : mockViewState),
useViewStoreApi: () => ({ getState: () => mockViewState, setState: vi.fn(), subscribe: vi.fn() }),
}));
-// Mock issues scope store
vi.mock("@multica/core/issues/stores/issues-scope-store", () => ({
useIssuesScopeStore: Object.assign(
(selector?: any) => {
@@ -224,7 +171,6 @@ vi.mock("@multica/core/issues/stores/issues-scope-store", () => ({
),
}));
-// Mock selection store
vi.mock("@multica/core/issues/stores/selection-store", () => ({
useIssueSelectionStore: Object.assign(
(selector?: any) => {
@@ -235,31 +181,6 @@ vi.mock("@multica/core/issues/stores/selection-store", () => ({
),
}));
-// Mock issue config
-vi.mock("@multica/core/issues/config", () => ({
- ALL_STATUSES: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],
- BOARD_STATUSES: ["backlog", "todo", "in_progress", "in_review", "done", "blocked"],
- STATUS_ORDER: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],
- STATUS_CONFIG: {
- backlog: { label: "Backlog", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
- todo: { label: "Todo", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
- in_progress: { label: "In Progress", iconColor: "text-warning", hoverBg: "hover:bg-warning/10" },
- in_review: { label: "In Review", iconColor: "text-success", hoverBg: "hover:bg-success/10" },
- done: { label: "Done", iconColor: "text-info", hoverBg: "hover:bg-info/10" },
- blocked: { label: "Blocked", iconColor: "text-destructive", hoverBg: "hover:bg-destructive/10" },
- cancelled: { label: "Cancelled", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
- },
- PRIORITY_ORDER: ["urgent", "high", "medium", "low", "none"],
- PRIORITY_CONFIG: {
- urgent: { label: "Urgent", bars: 4, color: "text-destructive" },
- high: { label: "High", bars: 3, color: "text-warning" },
- medium: { label: "Medium", bars: 2, color: "text-warning" },
- low: { label: "Low", bars: 1, color: "text-info" },
- none: { label: "No priority", bars: 0, color: "text-muted-foreground" },
- },
-}));
-
-// Mock modals
vi.mock("@multica/core/modals", () => ({
useModalStore: Object.assign(
() => ({ open: vi.fn() }),
@@ -267,11 +188,9 @@ vi.mock("@multica/core/modals", () => ({
),
}));
-vi.mock("@/features/modals", () => ({
- useModalStore: Object.assign(
- () => ({ open: vi.fn() }),
- { getState: () => ({ open: vi.fn() }) },
- ),
+// Mock sonner toast
+vi.mock("sonner", () => ({
+ toast: { error: vi.fn(), success: vi.fn() },
}));
// Mock dnd-kit
@@ -289,6 +208,7 @@ vi.mock("@dnd-kit/core", () => ({
vi.mock("@dnd-kit/sortable", () => ({
SortableContext: ({ children }: any) => children,
verticalListSortingStrategy: {},
+ arrayMove: vi.fn(),
useSortable: () => ({
attributes: {},
listeners: {},
@@ -303,6 +223,24 @@ vi.mock("@dnd-kit/utilities", () => ({
CSS: { Transform: { toString: () => undefined } },
}));
+// Mock @base-ui/react/accordion (used by ListView)
+vi.mock("@base-ui/react/accordion", () => ({
+ Accordion: Object.assign(
+ ({ children }: any) => <div>{children}</div>,
+ {
+ Root: ({ children }: any) => <div>{children}</div>,
+ Item: ({ children }: any) => <div>{children}</div>,
+ Header: ({ children }: any) => <div>{children}</div>,
+ Trigger: ({ children }: any) => <button>{children}</button>,
+ Panel: ({ children }: any) => <div>{children}</div>,
+ },
+ ),
+}));
+
+// ---------------------------------------------------------------------------
+// Test data
+// ---------------------------------------------------------------------------
+
const issueDefaults = {
parent_issue_id: null,
project_id: null,
@@ -366,20 +304,35 @@ const mockIssues: Issue[] = [
},
];
-import IssuesPage from "./page";
+// ---------------------------------------------------------------------------
+// Import component under test (after mocks)
+// ---------------------------------------------------------------------------
+
+import { IssuesPage } from "./issues-page";
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
function renderWithQuery(ui: React.ReactElement) {
- const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 }, mutations: { retry: false } } });
+ const qc = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, gcTime: 0 },
+ mutations: { retry: false },
+ },
+ });
return render(
<QueryClientProvider client={qc}>
- <WorkspaceIdProvider wsId="ws-1">
- {ui}
- </WorkspaceIdProvider>
+ <WorkspaceIdProvider wsId="ws-1">{ui}</WorkspaceIdProvider>
</QueryClientProvider>,
);
}
-describe("IssuesPage", () => {
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+describe("IssuesPage (shared)", () => {
beforeEach(() => {
vi.clearAllMocks();
mockListIssues.mockResolvedValue({ issues: [], total: 0 });
@@ -388,15 +341,20 @@ describe("IssuesPage", () => {
mockViewState.priorityFilters = [];
});
- it("shows loading state initially", () => {
+ it("shows loading skeletons initially", () => {
renderWithQuery(<IssuesPage />);
- expect(screen.getAllByRole("generic").some(el => el.getAttribute("data-slot") === "skeleton")).toBe(true);
+ expect(
+ screen.getAllByRole("generic").some((el) => el.getAttribute("data-slot") === "skeleton"),
+ ).toBe(true);
});
- it("renders issues in board view after loading", async () => {
- // issueListOptions makes 2 calls: open_only + closed page. Return issues for open, empty for closed.
+ it("renders issue titles after data loads", async () => {
mockListIssues.mockImplementation((params: any) =>
- Promise.resolve(params?.open_only ? { issues: mockIssues, total: mockIssues.length } : { issues: [], total: 0 }),
+ Promise.resolve(
+ params?.open_only
+ ? { issues: mockIssues, total: mockIssues.length }
+ : { issues: [], total: 0 },
+ ),
);
renderWithQuery(<IssuesPage />);
@@ -406,9 +364,13 @@ describe("IssuesPage", () => {
expect(screen.getByText("Write tests")).toBeInTheDocument();
});
- it("renders board columns", async () => {
+ it("renders board column headers", async () => {
mockListIssues.mockImplementation((params: any) =>
- Promise.resolve(params?.open_only ? { issues: mockIssues, total: mockIssues.length } : { issues: [], total: 0 }),
+ Promise.resolve(
+ params?.open_only
+ ? { issues: mockIssues, total: mockIssues.length }
+ : { issues: [], total: 0 },
+ ),
);
renderWithQuery(<IssuesPage />);
@@ -416,40 +378,37 @@ describe("IssuesPage", () => {
await screen.findByText("Backlog");
expect(screen.getAllByText("Todo").length).toBeGreaterThanOrEqual(1);
expect(screen.getAllByText("In Progress").length).toBeGreaterThanOrEqual(1);
- expect(screen.getAllByText("In Review").length).toBeGreaterThanOrEqual(1);
- expect(screen.getAllByText("Done").length).toBeGreaterThanOrEqual(1);
});
- it("shows workspace breadcrumb", async () => {
- renderWithQuery(<IssuesPage />);
-
- await screen.findByText("Issues");
- });
+ it("shows workspace breadcrumb with 'Issues' label", async () => {
+ mockListIssues.mockImplementation((params: any) =>
+ Promise.resolve(
+ params?.open_only
+ ? { issues: mockIssues, total: mockIssues.length }
+ : { issues: [], total: 0 },
+ ),
+ );
- it("shows scope buttons", async () => {
renderWithQuery(<IssuesPage />);
- await screen.findByText("All");
- expect(screen.getByText("Members")).toBeInTheDocument();
- expect(screen.getByText("Agents")).toBeInTheDocument();
+ await screen.findByText("Issues");
+ expect(screen.getByText("Test WS")).toBeInTheDocument();
});
- it("shows filter and display icon buttons", async () => {
- mockListIssues.mockImplementation((params: any) =>
- Promise.resolve(params?.open_only ? { issues: mockIssues, total: mockIssues.length } : { issues: [], total: 0 }),
- );
+ it("shows empty state when there are no issues", async () => {
+ mockListIssues.mockResolvedValue({ issues: [], total: 0 });
renderWithQuery(<IssuesPage />);
- await screen.findByText("Implement auth");
- const buttons = screen.getAllByRole("button");
- expect(buttons.length).toBeGreaterThan(0);
+ await screen.findByText("No issues yet");
+ expect(screen.getByText("Create an issue to get started.")).toBeInTheDocument();
});
- it("shows empty board view when no issues exist", () => {
+ it("shows scope tab buttons", async () => {
renderWithQuery(<IssuesPage />);
- // Should still render the board/list view, not a "no issues" message
- expect(screen.queryByText("No matching issues")).not.toBeInTheDocument();
+ await screen.findByText("All");
+ expect(screen.getByText("Members")).toBeInTheDocument();
+ expect(screen.getByText("Agents")).toBeInTheDocument();
});
});