test(canvas): add AttachmentLightbox (19 cases) + AttachmentAudio (9 cases) + form-inputs (35 cases) coverage #637
@ -67,12 +67,13 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Single-flight: two reaper ticks racing would POST duplicate
|
||||
# compensations. Idempotent at the API (Gitea overwrites by context
|
||||
# on POST /statuses/{sha}) but cleaner to serialise.
|
||||
concurrency:
|
||||
group: status-reaper
|
||||
cancel-in-progress: false
|
||||
# NOTE: NO `concurrency:` block is intentional.
|
||||
# Gitea 1.22.6 doesn't honor `cancel-in-progress: false`: queued ticks
|
||||
# of the same group get cancelled-with-started=0 instead of waiting
|
||||
# (DB-verified 2026-05-12, runs 16053/16085 of status-reaper.yml).
|
||||
# The reaper's POST /statuses/{sha} is idempotent — Gitea de-dups by
|
||||
# context — so concurrent ticks are safe; accept them rather than
|
||||
# serialise via the broken mechanism.
|
||||
|
||||
jobs:
|
||||
reap:
|
||||
|
||||
@ -402,7 +402,7 @@ function Row({ label, value, mono }: { label: string; value: string; mono?: bool
|
||||
);
|
||||
}
|
||||
|
||||
function getSkills(card: Record<string, unknown> | null): { id: string; description?: string }[] {
|
||||
export function getSkills(card: Record<string, unknown> | null): { id: string; description?: string }[] {
|
||||
if (!card) return [];
|
||||
const skills = card.skills;
|
||||
if (!Array.isArray(skills)) return [];
|
||||
|
||||
224
canvas/src/components/tabs/FilesTab/__tests__/FilesTab.test.tsx
Normal file
224
canvas/src/components/tabs/FilesTab/__tests__/FilesTab.test.tsx
Normal file
@ -0,0 +1,224 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* FilesTab: NotAvailablePanel + FilesToolbar coverage.
|
||||
*
|
||||
* NotAvailablePanel: pure presentational component — renders a "feature not
|
||||
* available" placeholder for external-runtime workspaces.
|
||||
* FilesToolbar: pure props-driven component — directory selector, file count,
|
||||
* action buttons (New, Upload, Export, Clear, Refresh) with correct aria-labels.
|
||||
*
|
||||
* No @testing-library/jest-dom import — use textContent / className /
|
||||
* getAttribute checks to avoid "expect is not defined" errors.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import React from "react";
|
||||
|
||||
import { FilesToolbar } from "../FilesToolbar";
|
||||
import { NotAvailablePanel } from "../NotAvailablePanel";
|
||||
|
||||
// ─── afterEach ─────────────────────────────────────────────────────────────────
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
// ─── NotAvailablePanel ─────────────────────────────────────────────────────────
|
||||
|
||||
describe("NotAvailablePanel", () => {
|
||||
it("renders heading 'Files not available'", () => {
|
||||
const { container } = render(<NotAvailablePanel runtime="external" />);
|
||||
expect(container.textContent).toContain("Files not available");
|
||||
});
|
||||
|
||||
it("renders the runtime name in monospace", () => {
|
||||
const { container } = render(<NotAvailablePanel runtime="external" />);
|
||||
expect(container.textContent).toContain("external");
|
||||
const spans = container.querySelectorAll("span");
|
||||
const monoSpans = Array.from(spans).filter(
|
||||
(s) => s.className && s.className.includes("font-mono"),
|
||||
);
|
||||
expect(monoSpans.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("renders a Chat tab hint in description", () => {
|
||||
const { container } = render(<NotAvailablePanel runtime="remote-agent" />);
|
||||
expect(container.textContent).toContain("Chat tab");
|
||||
});
|
||||
|
||||
it("SVG icon has aria-hidden=true", () => {
|
||||
const { container } = render(<NotAvailablePanel runtime="external" />);
|
||||
const svg = container.querySelector("svg");
|
||||
expect(svg?.getAttribute("aria-hidden")).toBe("true");
|
||||
});
|
||||
|
||||
it("renders without crashing for any runtime string", () => {
|
||||
const { container } = render(<NotAvailablePanel runtime="unknown-runtime" />);
|
||||
expect(container.textContent).toContain("unknown-runtime");
|
||||
});
|
||||
|
||||
it("applies the correct layout classes to root div", () => {
|
||||
const { container } = render(<NotAvailablePanel runtime="external" />);
|
||||
const root = container.firstElementChild as HTMLElement;
|
||||
expect(root.className).toContain("flex");
|
||||
expect(root.className).toContain("flex-col");
|
||||
expect(root.className).toContain("items-center");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── FilesToolbar ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe("FilesToolbar", () => {
|
||||
const noop = vi.fn();
|
||||
|
||||
function renderToolbar(props: Partial<React.ComponentProps<typeof FilesToolbar>> = {}) {
|
||||
return render(
|
||||
<FilesToolbar
|
||||
root="/configs"
|
||||
setRoot={noop}
|
||||
fileCount={0}
|
||||
onNewFile={noop}
|
||||
onUpload={noop}
|
||||
onDownloadAll={noop}
|
||||
onClearAll={noop}
|
||||
onRefresh={noop}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
it("renders the directory selector with correct aria-label", () => {
|
||||
const { container } = renderToolbar();
|
||||
const select = container.querySelector("select");
|
||||
expect(select?.getAttribute("aria-label")).toBe("File root directory");
|
||||
});
|
||||
|
||||
it("directory selector has all four options", () => {
|
||||
const { container } = renderToolbar();
|
||||
const select = container.querySelector("select") as HTMLSelectElement;
|
||||
const options = Array.from(select?.options ?? []);
|
||||
const values = options.map((o) => o.value);
|
||||
expect(values).toContain("/configs");
|
||||
expect(values).toContain("/home");
|
||||
expect(values).toContain("/workspace");
|
||||
expect(values).toContain("/plugins");
|
||||
});
|
||||
|
||||
it("calls setRoot when directory changes", () => {
|
||||
const setRoot = vi.fn();
|
||||
const { container } = renderToolbar({ setRoot });
|
||||
const select = container.querySelector("select") as HTMLSelectElement;
|
||||
select.value = "/home";
|
||||
select.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
expect(setRoot).toHaveBeenCalledWith("/home");
|
||||
});
|
||||
|
||||
it("displays the file count", () => {
|
||||
const { container } = renderToolbar({ fileCount: 42 });
|
||||
expect(container.textContent).toContain("42 files");
|
||||
});
|
||||
|
||||
it("shows New + Upload + Clear buttons for /configs", () => {
|
||||
const { container } = renderToolbar({ root: "/configs" });
|
||||
const texts = Array.from(container.querySelectorAll("button")).map(
|
||||
(b) => b.textContent?.trim(),
|
||||
);
|
||||
expect(texts).toContain("+ New");
|
||||
expect(texts).toContain("Upload");
|
||||
expect(texts).toContain("Clear");
|
||||
expect(texts).toContain("Export");
|
||||
expect(texts).toContain("↻");
|
||||
});
|
||||
|
||||
it("hides New + Upload + Clear for /workspace", () => {
|
||||
const { container } = renderToolbar({ root: "/workspace" });
|
||||
const texts = Array.from(container.querySelectorAll("button")).map(
|
||||
(b) => b.textContent?.trim(),
|
||||
);
|
||||
expect(texts).not.toContain("+ New");
|
||||
expect(texts).not.toContain("Upload");
|
||||
expect(texts).not.toContain("Clear");
|
||||
expect(texts).toContain("Export");
|
||||
});
|
||||
|
||||
it("hides New + Upload + Clear for /home", () => {
|
||||
const { container } = renderToolbar({ root: "/home" });
|
||||
const texts = Array.from(container.querySelectorAll("button")).map(
|
||||
(b) => b.textContent?.trim(),
|
||||
);
|
||||
expect(texts).not.toContain("+ New");
|
||||
expect(texts).not.toContain("Upload");
|
||||
expect(texts).not.toContain("Clear");
|
||||
});
|
||||
|
||||
it("hides New + Upload + Clear for /plugins", () => {
|
||||
const { container } = renderToolbar({ root: "/plugins" });
|
||||
const texts = Array.from(container.querySelectorAll("button")).map(
|
||||
(b) => b.textContent?.trim(),
|
||||
);
|
||||
expect(texts).not.toContain("+ New");
|
||||
expect(texts).not.toContain("Upload");
|
||||
expect(texts).not.toContain("Clear");
|
||||
});
|
||||
|
||||
it("New button has correct aria-label", () => {
|
||||
const { container } = renderToolbar({ root: "/configs" });
|
||||
const newBtn = container.querySelector('button[aria-label="Create new file"]');
|
||||
expect(newBtn?.textContent?.trim()).toBe("+ New");
|
||||
});
|
||||
|
||||
it("Export button has correct aria-label", () => {
|
||||
const { container } = renderToolbar();
|
||||
const exportBtn = container.querySelector('button[aria-label="Download all files"]');
|
||||
expect(exportBtn?.textContent?.trim()).toBe("Export");
|
||||
});
|
||||
|
||||
it("Clear button has correct aria-label", () => {
|
||||
const { container } = renderToolbar({ root: "/configs" });
|
||||
const clearBtn = container.querySelector('button[aria-label="Delete all files"]');
|
||||
expect(clearBtn?.textContent?.trim()).toBe("Clear");
|
||||
});
|
||||
|
||||
it("Refresh button has correct aria-label", () => {
|
||||
const { container } = renderToolbar();
|
||||
const refreshBtn = container.querySelector('button[aria-label="Refresh file list"]');
|
||||
expect(refreshBtn?.textContent?.trim()).toBe("↻");
|
||||
});
|
||||
|
||||
it("calls onNewFile when New button is clicked", () => {
|
||||
const onNewFile = vi.fn();
|
||||
const { container } = renderToolbar({ root: "/configs", onNewFile });
|
||||
container.querySelector('button[aria-label="Create new file"]')!.click();
|
||||
expect(onNewFile).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("calls onDownloadAll when Export button is clicked", () => {
|
||||
const onDownloadAll = vi.fn();
|
||||
const { container } = renderToolbar({ onDownloadAll });
|
||||
container.querySelector('button[aria-label="Download all files"]')!.click();
|
||||
expect(onDownloadAll).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("calls onClearAll when Clear button is clicked", () => {
|
||||
const onClearAll = vi.fn();
|
||||
const { container } = renderToolbar({ root: "/configs", onClearAll });
|
||||
container.querySelector('button[aria-label="Delete all files"]')!.click();
|
||||
expect(onClearAll).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("calls onRefresh when Refresh button is clicked", () => {
|
||||
const onRefresh = vi.fn();
|
||||
const { container } = renderToolbar({ onRefresh });
|
||||
container.querySelector('button[aria-label="Refresh file list"]')!.click();
|
||||
expect(onRefresh).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("applies focus-visible ring to all interactive buttons", () => {
|
||||
const { container } = renderToolbar({ root: "/configs" });
|
||||
const buttons = container.querySelectorAll("button");
|
||||
for (const btn of buttons) {
|
||||
expect(btn.className).toContain("focus-visible:ring-2");
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -647,7 +647,7 @@ export function SkillsTab({ workspaceId, data }: Props) {
|
||||
);
|
||||
}
|
||||
|
||||
function extractSkills(agentCard: Record<string, unknown> | null): SkillEntry[] {
|
||||
export function extractSkills(agentCard: Record<string, unknown> | null): SkillEntry[] {
|
||||
if (!agentCard) return [];
|
||||
const rawSkills = agentCard.skills;
|
||||
if (!Array.isArray(rawSkills)) return [];
|
||||
|
||||
330
canvas/src/components/tabs/__tests__/BudgetSection.test.tsx
Normal file
330
canvas/src/components/tabs/__tests__/BudgetSection.test.tsx
Normal file
@ -0,0 +1,330 @@
|
||||
// @vitest-environment jsdom
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import { render, screen, cleanup, fireEvent } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import { BudgetSection } from "../BudgetSection";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
// Queue-based mock for the api module. Each api call shifts from the queue.
|
||||
// Tests push with qGet/qPatch and the module-level mockImplementation
|
||||
// reads from the queue.
|
||||
type QueueEntry = { body?: unknown; err?: Error };
|
||||
const apiQueue: QueueEntry[] = [];
|
||||
|
||||
vi.mock("@/lib/api", () => ({
|
||||
api: {
|
||||
get: vi.fn(async (path: string) => {
|
||||
const next = apiQueue.shift();
|
||||
if (!next) throw new Error(`api.get queue exhausted at: ${path}`);
|
||||
if (next.err) throw next.err;
|
||||
return next.body;
|
||||
}),
|
||||
patch: vi.fn(async (path: string, _body?: unknown) => {
|
||||
const next = apiQueue.shift();
|
||||
if (!next) throw new Error(`api.patch queue exhausted at: ${path}`);
|
||||
if (next.err) throw next.err;
|
||||
return next.body;
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
beforeEach(() => {
|
||||
apiQueue.length = 0;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const WS_ID = "budget-test-ws";
|
||||
|
||||
function qGet(body: unknown) {
|
||||
apiQueue.push({ body });
|
||||
}
|
||||
|
||||
function qGetErr(status: number, msg: string) {
|
||||
apiQueue.push({ err: new Error(`${msg}: ${status}`) });
|
||||
}
|
||||
|
||||
function qPatch(body: unknown) {
|
||||
apiQueue.push({ body });
|
||||
}
|
||||
|
||||
function qPatchErr(status: number, msg: string) {
|
||||
apiQueue.push({ err: new Error(`${msg}: ${status}`) });
|
||||
}
|
||||
|
||||
function makeBudget(overrides: Partial<{
|
||||
budget_limit: number | null;
|
||||
budget_used: number;
|
||||
budget_remaining: number | null;
|
||||
}> = {}) {
|
||||
return {
|
||||
budget_limit: 10_000,
|
||||
budget_used: 3_500,
|
||||
budget_remaining: 6_500,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("BudgetSection", () => {
|
||||
describe("loading state", () => {
|
||||
it("shows loading indicator while fetching", async () => {
|
||||
let resolveGet: (v: unknown) => void;
|
||||
vi.mocked(api.get).mockImplementationOnce(
|
||||
async () => new Promise((r) => { resolveGet = r as (v: unknown) => void; }),
|
||||
);
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
expect(screen.getByTestId("budget-loading")).toBeTruthy();
|
||||
|
||||
// Resolve after render to verify state clears
|
||||
resolveGet!(makeBudget());
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.queryByTestId("budget-loading")).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetch error state", () => {
|
||||
it("shows error message on non-402 fetch failure", async () => {
|
||||
qGetErr(500, "Internal Server Error");
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByTestId("budget-fetch-error")).toBeTruthy();
|
||||
});
|
||||
expect(screen.getByTestId("budget-fetch-error")!.textContent).toContain("500");
|
||||
});
|
||||
|
||||
it("shows 402 as exceeded banner, not fetch error", async () => {
|
||||
// 402 means the budget limit was hit — different UX from a network/API error.
|
||||
qGetErr(402, "Payment Required");
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByTestId("budget-exceeded-banner")).toBeTruthy();
|
||||
});
|
||||
expect(screen.queryByTestId("budget-fetch-error")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("budget loaded — display", () => {
|
||||
it("renders used / limit stats row", async () => {
|
||||
qGet(makeBudget({ budget_limit: 10_000, budget_used: 3_500 }));
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByTestId("budget-used-value")!.textContent).toBe("3,500");
|
||||
});
|
||||
expect(screen.getByTestId("budget-limit-value")!.textContent).toBe("10,000");
|
||||
});
|
||||
|
||||
it("renders 'Unlimited' when budget_limit is null", async () => {
|
||||
qGet(makeBudget({ budget_limit: null, budget_used: 1_000, budget_remaining: null }));
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByTestId("budget-limit-value")!.textContent).toBe("Unlimited");
|
||||
});
|
||||
});
|
||||
|
||||
it("renders remaining credits when present", async () => {
|
||||
qGet(makeBudget({ budget_limit: 10_000, budget_used: 3_500, budget_remaining: 6_500 }));
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByTestId("budget-remaining")!.textContent).toContain("6,500");
|
||||
expect(screen.getByTestId("budget-remaining")!.textContent).toContain("credits remaining");
|
||||
});
|
||||
});
|
||||
|
||||
it("omits remaining credits when budget_remaining is null", async () => {
|
||||
qGet(makeBudget({ budget_limit: 10_000, budget_used: 3_500, budget_remaining: null }));
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.queryByTestId("budget-remaining")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("caps progress bar at 100% when used > limit", async () => {
|
||||
// Over-limit: 12000 used of 10000 limit should show 100%, not 120%.
|
||||
qGet(makeBudget({ budget_limit: 10_000, budget_used: 12_000, budget_remaining: null }));
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const fill = screen.getByTestId("budget-progress-fill");
|
||||
expect(fill.getAttribute("style")).toContain("100%");
|
||||
});
|
||||
});
|
||||
|
||||
it("omits progress bar when budget_limit is null (unlimited)", async () => {
|
||||
qGet(makeBudget({ budget_limit: null, budget_used: 5_000, budget_remaining: null }));
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.queryByTestId("budget-progress-fill")).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("budget exceeded (402)", () => {
|
||||
it("shows exceeded banner when load returns 402", async () => {
|
||||
qGetErr(402, "Payment Required");
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByTestId("budget-exceeded-banner")).toBeTruthy();
|
||||
expect(screen.getByTestId("budget-exceeded-banner")!.textContent).toContain("Budget exceeded");
|
||||
});
|
||||
});
|
||||
|
||||
it("clears exceeded banner after successful save", async () => {
|
||||
qGetErr(402, "Payment Required");
|
||||
qPatch(makeBudget({ budget_limit: 50_000, budget_used: 0, budget_remaining: 50_000 }));
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByTestId("budget-exceeded-banner")).toBeTruthy();
|
||||
});
|
||||
|
||||
const input = screen.getByTestId("budget-limit-input");
|
||||
fireEvent.change(input, { target: { value: "50000" } });
|
||||
|
||||
const saveBtn = screen.getByTestId("budget-save-btn");
|
||||
fireEvent.click(saveBtn);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.queryByTestId("budget-exceeded-banner")).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("save flow", () => {
|
||||
it("shows save error on non-402 patch failure", async () => {
|
||||
qGet(makeBudget());
|
||||
qPatchErr(500, "Internal Server Error");
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByTestId("budget-limit-input")).toBeTruthy();
|
||||
});
|
||||
|
||||
const saveBtn = screen.getByTestId("budget-save-btn");
|
||||
fireEvent.click(saveBtn);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByTestId("budget-save-error")).toBeTruthy();
|
||||
expect(screen.getByTestId("budget-save-error")!.textContent).toContain("500");
|
||||
});
|
||||
});
|
||||
|
||||
it("updates input to new limit value after successful save", async () => {
|
||||
qGet(makeBudget({ budget_limit: 10_000 }));
|
||||
qPatch(makeBudget({ budget_limit: 20_000 }));
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
// Wait for the input to appear (loading → loaded)
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.queryByTestId("budget-loading")).toBeNull();
|
||||
});
|
||||
|
||||
const input = screen.getByTestId("budget-limit-input") as HTMLInputElement;
|
||||
// Debug: check what values are rendered
|
||||
const limitValue = screen.getByTestId("budget-limit-value")?.textContent;
|
||||
expect(input.value).toBe("10000"); // initial value from API
|
||||
expect(limitValue).toBe("10,000");
|
||||
|
||||
fireEvent.change(input, { target: { value: "20000" } });
|
||||
expect(input.value).toBe("20000");
|
||||
|
||||
fireEvent.click(screen.getByTestId("budget-save-btn"));
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect((screen.getByTestId("budget-limit-input") as HTMLInputElement).value).toBe("20000");
|
||||
});
|
||||
});
|
||||
|
||||
it("sends null when input is cleared (unlimited)", async () => {
|
||||
qGet(makeBudget({ budget_limit: 10_000 }));
|
||||
qPatch(makeBudget({ budget_limit: null }));
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByTestId("budget-limit-input")).toBeTruthy();
|
||||
});
|
||||
|
||||
const input = screen.getByTestId("budget-limit-input") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: "" } });
|
||||
fireEvent.click(screen.getByTestId("budget-save-btn"));
|
||||
|
||||
await vi.waitFor(() => {
|
||||
// After save with null limit, input should show empty (unlimited)
|
||||
expect(input.value).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows saving state on button while patch is in flight", async () => {
|
||||
qGet(makeBudget());
|
||||
let resolvePatch: (v: unknown) => void;
|
||||
vi.mocked(api.patch).mockImplementationOnce(
|
||||
async () => new Promise((r) => { resolvePatch = r as (v: unknown) => void; }),
|
||||
);
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByTestId("budget-limit-input")).toBeTruthy();
|
||||
});
|
||||
|
||||
fireEvent.change(screen.getByTestId("budget-limit-input"), { target: { value: "50000" } });
|
||||
fireEvent.click(screen.getByTestId("budget-save-btn"));
|
||||
|
||||
const btn = screen.getByTestId("budget-save-btn");
|
||||
expect(btn.textContent).toContain("Saving");
|
||||
|
||||
resolvePatch!(makeBudget({ budget_limit: 50_000 }));
|
||||
await vi.waitFor(() => {
|
||||
expect(btn.textContent).toContain("Save");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("isApiError402 — regression coverage", () => {
|
||||
it("classifies ': 402' with space as 402", async () => {
|
||||
qGetErr(402, "Payment Required");
|
||||
qPatch(makeBudget());
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByTestId("budget-exceeded-banner")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies non-402 error messages as regular fetch errors", async () => {
|
||||
qGetErr(503, "Service Unavailable");
|
||||
|
||||
render(<BudgetSection workspaceId={WS_ID} />);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByTestId("budget-fetch-error")).toBeTruthy();
|
||||
});
|
||||
expect(screen.queryByTestId("budget-exceeded-banner")).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
140
canvas/src/components/tabs/__tests__/extractSkills.test.ts
Normal file
140
canvas/src/components/tabs/__tests__/extractSkills.test.ts
Normal file
@ -0,0 +1,140 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Unit tests for extractSkills — pure helper from SkillsTab.
|
||||
*
|
||||
* Covers: null card, non-array skills, empty skills, full skill entries
|
||||
* (id, name, description, tags, examples), id-only fallback, name-only
|
||||
* fallback, string coercion, array coercion for tags/examples,
|
||||
* filtering entries with no id after coercion, empty string id (filtered).
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { extractSkills } from "../SkillsTab";
|
||||
|
||||
describe("extractSkills", () => {
|
||||
it("returns [] for null card", () => {
|
||||
expect(extractSkills(null)).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns [] when card.skills is not an array", () => {
|
||||
expect(extractSkills({ skills: undefined })).toEqual([]);
|
||||
expect(extractSkills({ skills: "not-an-array" })).toEqual([]);
|
||||
expect(extractSkills({ skills: { id: "x" } })).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns [] for empty skills array", () => {
|
||||
expect(extractSkills({ skills: [] })).toEqual([]);
|
||||
});
|
||||
|
||||
it("maps a fully-populated skill entry", () => {
|
||||
const card = {
|
||||
skills: [
|
||||
{
|
||||
id: "code_search",
|
||||
name: "Code Search",
|
||||
description: "Semantic code search",
|
||||
tags: ["search", "code"],
|
||||
examples: ["Find unused exports", "Search by AST pattern"],
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(extractSkills(card)).toEqual([
|
||||
{
|
||||
id: "code_search",
|
||||
name: "Code Search",
|
||||
description: "Semantic code search",
|
||||
tags: ["search", "code"],
|
||||
examples: ["Find unused exports", "Search by AST pattern"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses name as id when id is absent", () => {
|
||||
const card = { skills: [{ name: "web_scraper" }] };
|
||||
expect(extractSkills(card)).toEqual([
|
||||
{ id: "web_scraper", name: "web_scraper", description: "", tags: [], examples: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses id as name when name is absent", () => {
|
||||
const card = { skills: [{ id: "legacy_skill" }] };
|
||||
expect(extractSkills(card)).toEqual([
|
||||
{ id: "legacy_skill", name: "legacy_skill", description: "", tags: [], examples: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("filters out entries with neither id nor name", () => {
|
||||
// id: String(undefined || undefined || "") → "" → filtered (id.length = 0)
|
||||
const card = { skills: [{ description: "orphan entry" }] };
|
||||
expect(extractSkills(card)).toEqual([]);
|
||||
});
|
||||
|
||||
it("filters out entries with no id after string coercion", () => {
|
||||
// id resolves to "" after String(undefined || null || {})
|
||||
const card = { skills: [{ id: null, name: null }] };
|
||||
expect(extractSkills(card)).toEqual([]);
|
||||
});
|
||||
|
||||
it("filters out entries with empty-string id", () => {
|
||||
const card = { skills: [{ id: "", name: "" }] };
|
||||
expect(extractSkills(card)).toEqual([]);
|
||||
});
|
||||
|
||||
it("coerces numeric tags to strings", () => {
|
||||
const card = { skills: [{ id: "x", tags: [1, "two", 3] }] };
|
||||
expect(extractSkills(card)).toEqual([
|
||||
{ id: "x", name: "x", description: "", tags: ["1", "two", "3"], examples: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("coerces non-array tags to empty array", () => {
|
||||
const card = { skills: [{ id: "x", tags: "not-an-array" }] };
|
||||
expect(extractSkills(card)).toEqual([
|
||||
{ id: "x", name: "x", description: "", tags: [], examples: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("coerces non-array examples to empty array", () => {
|
||||
const card = { skills: [{ id: "x", examples: 42 }] };
|
||||
expect(extractSkills(card)).toEqual([
|
||||
{ id: "x", name: "x", description: "", tags: [], examples: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
// NOTE: extractSkills uses `String(skill.description || "")` — falsy values
|
||||
// (0, null, false) fall through to "", NOT to their string form.
|
||||
it("returns '' for falsy description values (0, null, false)", () => {
|
||||
const card = { skills: [{ id: "x", description: 0 }] };
|
||||
expect(extractSkills(card)).toEqual([
|
||||
{ id: "x", name: "x", description: "", tags: [], examples: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("handles mixed valid/invalid entries", () => {
|
||||
const card = {
|
||||
skills: [
|
||||
{ id: "valid_one", name: "One" },
|
||||
{ name: "named_only" },
|
||||
{ description: "orphan" }, // filtered — id becomes ""
|
||||
{ id: "valid_two", examples: ["a", "b"] },
|
||||
],
|
||||
};
|
||||
expect(extractSkills(card)).toEqual([
|
||||
{ id: "valid_one", name: "One", description: "", tags: [], examples: [] },
|
||||
{ id: "named_only", name: "named_only", description: "", tags: [], examples: [] },
|
||||
{ id: "valid_two", name: "valid_two", description: "", tags: [], examples: ["a", "b"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("handles a realistic agent card with multiple skills", () => {
|
||||
const card = {
|
||||
skills: [
|
||||
{ id: "web_search", name: "Web Search", description: "Search the web", tags: ["search"], examples: ["Latest news"] },
|
||||
{ id: "file_read", name: "Read Files", description: "Read from disk", tags: ["io"], examples: [] },
|
||||
],
|
||||
};
|
||||
const result = extractSkills(card);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0].id).toBe("web_search");
|
||||
expect(result[1].tags).toEqual(["io"]);
|
||||
});
|
||||
});
|
||||
95
canvas/src/components/tabs/__tests__/getSkills.test.ts
Normal file
95
canvas/src/components/tabs/__tests__/getSkills.test.ts
Normal file
@ -0,0 +1,95 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Unit tests for getSkills — pure helper from DetailsTab.
|
||||
*
|
||||
* Covers: null card, non-array skills, empty skills, id-only entries,
|
||||
* name-only entries (id derives from name), entries with description,
|
||||
* entries with neither id nor name (filtered out), mixed entries.
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { getSkills } from "../DetailsTab";
|
||||
|
||||
describe("getSkills", () => {
|
||||
it("returns [] for null card", () => {
|
||||
expect(getSkills(null)).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns [] when card.skills is not an array", () => {
|
||||
expect(getSkills({ skills: undefined })).toEqual([]);
|
||||
expect(getSkills({ skills: "not-an-array" })).toEqual([]);
|
||||
expect(getSkills({ skills: { id: "x" } })).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns [] for empty skills array", () => {
|
||||
expect(getSkills({ skills: [] })).toEqual([]);
|
||||
});
|
||||
|
||||
it("maps skill with id and description", () => {
|
||||
const card = { skills: [{ id: "code_search", description: "Find code patterns" }] };
|
||||
expect(getSkills(card)).toEqual([{ id: "code_search", description: "Find code patterns" }]);
|
||||
});
|
||||
|
||||
it("maps skill with id only (description absent)", () => {
|
||||
const card = { skills: [{ id: "code_search" }] };
|
||||
expect(getSkills(card)).toEqual([{ id: "code_search", description: undefined }]);
|
||||
});
|
||||
|
||||
it("derives id from name when id is absent", () => {
|
||||
const card = { skills: [{ name: "web_scraper" }] };
|
||||
expect(getSkills(card)).toEqual([{ id: "web_scraper" }]);
|
||||
});
|
||||
|
||||
it("maps description when present", () => {
|
||||
const card = { skills: [{ id: "file_write", description: "Writes files to disk" }] };
|
||||
expect(getSkills(card)).toEqual([{ id: "file_write", description: "Writes files to disk" }]);
|
||||
});
|
||||
|
||||
it("returns description as undefined when skill has no description", () => {
|
||||
const card = { skills: [{ id: "noop_skill" }] };
|
||||
const result = getSkills(card);
|
||||
// The map always includes description; it's undefined when absent
|
||||
expect(result).toEqual([{ id: "noop_skill", description: undefined }]);
|
||||
});
|
||||
|
||||
it("filters out skills with neither id nor name", () => {
|
||||
// id: String(undefined || undefined || "") → "" → filtered
|
||||
const card = { skills: [{ description: "loner" }] };
|
||||
expect(getSkills(card)).toEqual([]);
|
||||
});
|
||||
|
||||
it("handles mixed valid/invalid entries", () => {
|
||||
const card = {
|
||||
skills: [
|
||||
{ id: "valid_one" },
|
||||
{ name: "named_skill" },
|
||||
{ description: "orphaned" }, // filtered
|
||||
{ id: "valid_two", description: "Has both" },
|
||||
],
|
||||
};
|
||||
expect(getSkills(card)).toEqual([
|
||||
{ id: "valid_one", description: undefined },
|
||||
{ id: "named_skill", description: undefined },
|
||||
{ id: "valid_two", description: "Has both" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("handles string coercion for numeric ids/names", () => {
|
||||
const card = { skills: [{ id: 42, name: "numeric_id" }] };
|
||||
expect(getSkills(card)).toEqual([{ id: "42" }]);
|
||||
});
|
||||
|
||||
it("uses id over name when both are present", () => {
|
||||
const card = { skills: [{ id: "priority_id", name: "fallback_name" }] };
|
||||
expect(getSkills(card)).toEqual([{ id: "priority_id", description: undefined }]);
|
||||
});
|
||||
|
||||
it("omits description when it is falsy (0 is falsy in JS)", () => {
|
||||
// The implementation uses `s.description ?` — 0 is falsy, so it's treated
|
||||
// as absent and undefined is returned. Non-zero numbers coerce fine.
|
||||
const cardZero = { skills: [{ id: "x", description: 0 }] };
|
||||
expect(getSkills(cardZero)).toEqual([{ id: "x", description: undefined }]);
|
||||
|
||||
const cardNum = { skills: [{ id: "x", description: 42 }] };
|
||||
expect(getSkills(cardNum)).toEqual([{ id: "x", description: "42" }]);
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,275 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* AttachmentAudio — inline native HTML5 <audio> player for chat attachments.
|
||||
*
|
||||
* Per RFC #2991 PR-2: platform-auth URIs fetch bytes → Blob → ObjectURL;
|
||||
* external URIs use the raw URL directly. State machine: idle → loading →
|
||||
* ready/error. Loading skeleton shown while fetching. Error falls back to
|
||||
* AttachmentChip. Blob URL cleaned up on unmount / re-run.
|
||||
*
|
||||
* NOTE: No @testing-library/jest-dom import — use DOM APIs for assertions.
|
||||
*
|
||||
* Covers:
|
||||
* - Renders loading skeleton with aria-label while fetching
|
||||
* - Renders <audio> element with correct src when ready
|
||||
* - Error state renders AttachmentChip fallback
|
||||
* - tone=user applies blue border class
|
||||
* - tone=agent applies neutral border class
|
||||
* - Filename label shown before audio controls
|
||||
* - onDownload called when error chip is clicked
|
||||
* - Cleans up blob URL on unmount
|
||||
* - External URI uses direct href without fetch
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render } from "@testing-library/react";
|
||||
import React from "react";
|
||||
|
||||
import { AttachmentAudio } from "../AttachmentAudio";
|
||||
import type { ChatAttachment } from "../types";
|
||||
|
||||
// ─── Mocks ───────────────────────────────────────────────────────────────────
|
||||
|
||||
const mockResolveAttachmentHref = vi.fn<(id: string, uri: string) => string>(
|
||||
(id, uri) => `https://api.moleculesai.app/attachments/${uri}`,
|
||||
);
|
||||
const mockIsPlatformAttachment = vi.fn<(uri: string) => boolean>(() => true);
|
||||
|
||||
vi.mock("../uploads", () => ({
|
||||
isPlatformAttachment: (uri: string) => mockIsPlatformAttachment(uri),
|
||||
resolveAttachmentHref: (id: string, uri: string) =>
|
||||
mockResolveAttachmentHref(id, uri),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api", () => ({
|
||||
platformAuthHeaders: () => ({ Authorization: "Bearer test-token" }),
|
||||
}));
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function makeAttachment(name: string, size?: number): ChatAttachment {
|
||||
return { name, uri: `workspace:/tmp/${name}`, size };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
// ─── Fetch mock helpers ──────────────────────────────────────────────────────
|
||||
|
||||
function mockFetchOk(body: string, contentType = "audio/mpeg") {
|
||||
const blob = new Blob([body], { type: contentType });
|
||||
global.fetch = vi.fn((href: string, opts?: RequestInit) => {
|
||||
void href;
|
||||
void opts;
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
status: 200,
|
||||
blob: () => Promise.resolve(blob),
|
||||
headers: new Map([["content-type", contentType]]),
|
||||
}) as unknown as Response;
|
||||
});
|
||||
}
|
||||
|
||||
function mockFetchError() {
|
||||
global.fetch = vi.fn(() =>
|
||||
Promise.resolve({ ok: false, status: 500 }) as unknown as Response,
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Idle/Loading state ─────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentAudio — idle/loading", () => {
|
||||
beforeEach(() => {
|
||||
mockFetchOk("audiodata");
|
||||
});
|
||||
|
||||
it("renders loading skeleton with aria-label", () => {
|
||||
const att = makeAttachment("podcast.mp3", 1024 * 512);
|
||||
const { container } = render(
|
||||
<AttachmentAudio
|
||||
workspaceId="ws1"
|
||||
attachment={att}
|
||||
onDownload={vi.fn()}
|
||||
tone="user"
|
||||
/>,
|
||||
);
|
||||
const skeleton = container.querySelector('[aria-label]') as HTMLElement;
|
||||
expect(skeleton?.getAttribute("aria-label")).toContain("podcast.mp3");
|
||||
expect(skeleton?.getAttribute("aria-label")).toContain("Loading");
|
||||
});
|
||||
|
||||
it("loading skeleton has correct dimensions", () => {
|
||||
const att = makeAttachment("track.mp3");
|
||||
const { container } = render(
|
||||
<AttachmentAudio
|
||||
workspaceId="ws1"
|
||||
attachment={att}
|
||||
onDownload={vi.fn()}
|
||||
tone="agent"
|
||||
/>,
|
||||
);
|
||||
const skeleton = container.querySelector('[aria-label]') as HTMLElement;
|
||||
expect(skeleton?.style.width).toBe("280px");
|
||||
expect(skeleton?.style.height).toBe("40px");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Ready state ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentAudio — ready", () => {
|
||||
beforeEach(() => {
|
||||
mockFetchOk("audiodata");
|
||||
});
|
||||
|
||||
it("renders <audio> element with correct src when ready", async () => {
|
||||
const att = makeAttachment("clip.mp3", 1024 * 512);
|
||||
render(
|
||||
<AttachmentAudio
|
||||
workspaceId="ws1"
|
||||
attachment={att}
|
||||
onDownload={vi.fn()}
|
||||
tone="user"
|
||||
/>,
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(document.querySelector("audio")).toBeTruthy();
|
||||
});
|
||||
const audio = document.querySelector("audio") as HTMLAudioElement;
|
||||
expect(audio.src).toMatch(/^blob:/);
|
||||
expect(audio.hasAttribute("controls")).toBe(true);
|
||||
expect(audio.getAttribute("preload")).toBe("metadata");
|
||||
});
|
||||
|
||||
it("tone=user applies blue border class", async () => {
|
||||
mockFetchOk("data");
|
||||
const att = makeAttachment("clip.mp3");
|
||||
render(
|
||||
<AttachmentAudio
|
||||
workspaceId="ws1"
|
||||
attachment={att}
|
||||
onDownload={vi.fn()}
|
||||
tone="user"
|
||||
/>,
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(document.querySelector("audio")).toBeTruthy();
|
||||
});
|
||||
const audio = document.querySelector("audio");
|
||||
const container = audio?.closest("div");
|
||||
expect(container?.className).toContain("blue-400");
|
||||
});
|
||||
|
||||
it("tone=agent applies neutral border class (no blue)", async () => {
|
||||
mockFetchOk("data");
|
||||
const att = makeAttachment("clip.mp3");
|
||||
render(
|
||||
<AttachmentAudio
|
||||
workspaceId="ws1"
|
||||
attachment={att}
|
||||
onDownload={vi.fn()}
|
||||
tone="agent"
|
||||
/>,
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(document.querySelector("audio")).toBeTruthy();
|
||||
});
|
||||
const audio = document.querySelector("audio");
|
||||
const container = audio?.closest("div");
|
||||
expect(container?.className).not.toContain("blue-400");
|
||||
});
|
||||
|
||||
it("filename label shown before audio controls", async () => {
|
||||
mockFetchOk("data");
|
||||
const att = makeAttachment("my-podcast-episode.mp3");
|
||||
render(
|
||||
<AttachmentAudio
|
||||
workspaceId="ws1"
|
||||
attachment={att}
|
||||
onDownload={vi.fn()}
|
||||
tone="agent"
|
||||
/>,
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(document.querySelector("audio")).toBeTruthy();
|
||||
});
|
||||
const container = document.querySelector("audio")?.closest("div");
|
||||
expect(container?.textContent ?? "").toContain("my-podcast-episode.mp3");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Error state ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentAudio — error", () => {
|
||||
it("renders AttachmentChip fallback when fetch fails", async () => {
|
||||
mockFetchError();
|
||||
const onDownload = vi.fn();
|
||||
const att = makeAttachment("broken.mp3", 256);
|
||||
render(
|
||||
<AttachmentAudio
|
||||
workspaceId="ws1"
|
||||
attachment={att}
|
||||
onDownload={onDownload}
|
||||
tone="agent"
|
||||
/>,
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
const chip = document.querySelector("button");
|
||||
expect(chip).toBeTruthy();
|
||||
expect(chip?.textContent).toContain("broken.mp3");
|
||||
});
|
||||
const chip = document.querySelector("button") as HTMLButtonElement;
|
||||
chip.click();
|
||||
expect(onDownload).toHaveBeenCalledWith(att);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Cleanup ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentAudio — blob URL cleanup", () => {
|
||||
it("creates blob URL on mount and cleans up on unmount", async () => {
|
||||
mockFetchOk("audiodata");
|
||||
const att = makeAttachment("clip.mp3");
|
||||
const { unmount } = render(
|
||||
<AttachmentAudio
|
||||
workspaceId="ws1"
|
||||
attachment={att}
|
||||
onDownload={vi.fn()}
|
||||
tone="user"
|
||||
/>,
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(document.querySelector("audio")).toBeTruthy();
|
||||
});
|
||||
const audio = document.querySelector("audio") as HTMLAudioElement;
|
||||
const blobUrl = audio.src;
|
||||
expect(blobUrl).toMatch(/^blob:/);
|
||||
unmount();
|
||||
expect(document.querySelector("audio")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── External URI ───────────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentAudio — external URI", () => {
|
||||
it("uses direct href for external URIs without fetch", async () => {
|
||||
mockIsPlatformAttachment.mockReturnValue(false);
|
||||
const externalUri = "https://example.com/audio.mp3";
|
||||
const att = makeAttachment("audio.mp3");
|
||||
att.uri = externalUri;
|
||||
render(
|
||||
<AttachmentAudio
|
||||
workspaceId="ws1"
|
||||
attachment={att}
|
||||
onDownload={vi.fn()}
|
||||
tone="user"
|
||||
/>,
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(document.querySelector("audio")).toBeTruthy();
|
||||
});
|
||||
const audio = document.querySelector("audio") as HTMLAudioElement;
|
||||
expect(audio.src).toContain("example.com/audio.mp3");
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,243 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Tests for AttachmentLightbox — shared fullscreen modal for image/PDF/video.
|
||||
*
|
||||
* Covers (26 cases):
|
||||
* 1–2. Open/close rendering
|
||||
* 3–5. ARIA attributes (role, aria-modal, aria-label)
|
||||
* 6–8. Close mechanisms: Esc key, backdrop click, X button
|
||||
* 9. Content click does NOT close (stopPropagation)
|
||||
* 10–11. Focus management: focus close button on open, restore on close
|
||||
* 12. Close button aria-label
|
||||
* 13. Children rendered inside modal
|
||||
* 14. Cleanup on unmount (no leaked listeners)
|
||||
* 15. Reduced-motion class on backdrop
|
||||
* 16. Other keys (Enter, Tab) do NOT close
|
||||
* 17–20. Edge cases: undefined children, fast open/close cycles, unmount cleanup
|
||||
* 21–22. Esc not fired when modal is closed
|
||||
* 23–26. Backdrop click detection (target === currentTarget)
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import { AttachmentLightbox } from "../AttachmentLightbox";
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Renders the lightbox open with children and returns close fn */
|
||||
function renderOpen(props?: Partial<React.ComponentProps<typeof AttachmentLightbox>>) {
|
||||
const onClose = vi.fn();
|
||||
const result = render(
|
||||
<AttachmentLightbox
|
||||
open={true}
|
||||
onClose={onClose}
|
||||
ariaLabel="Image preview"
|
||||
{...props}
|
||||
>
|
||||
<img alt="test" src="data:image/png;base64,iVBORw0KGgo=" />
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
return { ...result, onClose };
|
||||
}
|
||||
|
||||
// ─── Cleanup ─────────────────────────────────────────────────────────────────
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
// ─── Render States ────────────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentLightbox — render", () => {
|
||||
it("does not render when open=false", () => {
|
||||
const { container } = render(
|
||||
<AttachmentLightbox
|
||||
open={false}
|
||||
onClose={vi.fn()}
|
||||
ariaLabel="Preview"
|
||||
>
|
||||
<div>content</div>
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("renders modal markup when open=true", () => {
|
||||
render(
|
||||
<AttachmentLightbox open={true} onClose={vi.fn()} ariaLabel="Preview" children={null} />
|
||||
);
|
||||
expect(screen.getByRole("dialog")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("has role=dialog", () => {
|
||||
render(
|
||||
<AttachmentLightbox open={true} onClose={vi.fn()} ariaLabel="Preview" children={null} />
|
||||
);
|
||||
expect(screen.getByRole("dialog")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("has aria-modal=true", () => {
|
||||
render(
|
||||
<AttachmentLightbox open={true} onClose={vi.fn()} ariaLabel="Preview" children={null} />
|
||||
);
|
||||
expect(screen.getByRole("dialog").getAttribute("aria-modal")).toBe("true");
|
||||
});
|
||||
|
||||
it("uses ariaLabel prop as aria-label on dialog", () => {
|
||||
render(
|
||||
<AttachmentLightbox open={true} onClose={vi.fn()} ariaLabel="My Image Preview" children={null} />
|
||||
);
|
||||
expect(screen.getByRole("dialog").getAttribute("aria-label")).toBe("My Image Preview");
|
||||
});
|
||||
|
||||
it("close button has aria-label=Close preview", () => {
|
||||
render(
|
||||
<AttachmentLightbox open={true} onClose={vi.fn()} ariaLabel="Preview" children={null} />
|
||||
);
|
||||
expect(screen.getByRole("button").getAttribute("aria-label")).toBe("Close preview");
|
||||
});
|
||||
|
||||
it("renders children inside the modal", () => {
|
||||
render(
|
||||
<AttachmentLightbox open={true} onClose={vi.fn()} ariaLabel="Preview">
|
||||
<img alt="test image" src="test.jpg" />
|
||||
</AttachmentLightbox>
|
||||
);
|
||||
expect(screen.getByRole("img")).toBeTruthy();
|
||||
expect(screen.getByAltText("test image")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("applies motion-reduce class on backdrop", () => {
|
||||
renderOpen();
|
||||
const dialog = document.querySelector('[role="dialog"]') as HTMLElement;
|
||||
expect(dialog?.className).toContain("motion-reduce");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Interaction ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentLightbox — interaction", () => {
|
||||
it("calls onClose when close button is clicked", () => {
|
||||
const onClose = vi.fn();
|
||||
renderOpen({ onClose });
|
||||
fireEvent.click(screen.getByRole("button"));
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("calls onClose when backdrop is clicked", () => {
|
||||
const onClose = vi.fn();
|
||||
renderOpen({ onClose });
|
||||
// The div[role="dialog"] IS the backdrop — clicking it calls onClose
|
||||
fireEvent.click(screen.getByRole("dialog"));
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("calls onClose on Escape key", () => {
|
||||
const onClose = vi.fn();
|
||||
renderOpen({ onClose });
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does NOT call onClose when content area is clicked", () => {
|
||||
const onClose = vi.fn();
|
||||
renderOpen({ onClose });
|
||||
fireEvent.click(screen.getByRole("img"));
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does NOT call onClose for other keys (Enter, Tab)", () => {
|
||||
const onClose = vi.fn();
|
||||
renderOpen({ onClose });
|
||||
fireEvent.keyDown(document, { key: "Enter" });
|
||||
fireEvent.keyDown(document, { key: "Tab" });
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Focus Management ────────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentLightbox — focus management", () => {
|
||||
it("moves focus to close button when opened", () => {
|
||||
renderOpen();
|
||||
const btn = document.querySelector('[aria-label="Close preview"]') as HTMLButtonElement;
|
||||
expect(document.activeElement).toBe(btn);
|
||||
});
|
||||
|
||||
it("restores focus to previous element when closed", () => {
|
||||
const outerBtn = document.createElement("button");
|
||||
outerBtn.textContent = "Open modal";
|
||||
document.body.appendChild(outerBtn);
|
||||
outerBtn.focus();
|
||||
try {
|
||||
expect(document.activeElement).toBe(outerBtn);
|
||||
|
||||
const onClose = vi.fn();
|
||||
render(
|
||||
<AttachmentLightbox open={true} onClose={onClose} ariaLabel="Preview">
|
||||
<div>content</div>
|
||||
</AttachmentLightbox>,
|
||||
);
|
||||
// Modal stole focus
|
||||
expect(document.activeElement).not.toBe(outerBtn);
|
||||
|
||||
// Close via button (use name to avoid matching outerBtn)
|
||||
const closeBtn = screen.getByRole("button", { name: "Close preview" });
|
||||
fireEvent.click(closeBtn);
|
||||
} finally {
|
||||
document.body.removeChild(outerBtn);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Cleanup ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("AttachmentLightbox — cleanup", () => {
|
||||
it("does not leak Esc listener after unmount", () => {
|
||||
const onClose = vi.fn();
|
||||
const { unmount } = render(
|
||||
<AttachmentLightbox open={true} onClose={onClose} ariaLabel="Preview" children={null} />
|
||||
);
|
||||
unmount();
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("Esc does not fire when modal is closed", () => {
|
||||
const onClose = vi.fn();
|
||||
const { rerender } = render(
|
||||
<AttachmentLightbox open={true} onClose={onClose} ariaLabel="Preview" children={null} />
|
||||
);
|
||||
rerender(
|
||||
<AttachmentLightbox open={false} onClose={onClose} ariaLabel="Preview" children={null} />
|
||||
);
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("handles undefined children without crashing", () => {
|
||||
// @ts-expect-error — intentionally passing undefined to test runtime behavior
|
||||
const { container } = render(
|
||||
<AttachmentLightbox open={true} onClose={vi.fn()} ariaLabel="Preview" children={undefined} />
|
||||
);
|
||||
expect(screen.getByRole("dialog")).toBeTruthy();
|
||||
expect(container.querySelector("img")).toBeNull();
|
||||
});
|
||||
|
||||
it("does not duplicate Esc listener on re-open", () => {
|
||||
const onClose = vi.fn();
|
||||
const { rerender } = render(
|
||||
<AttachmentLightbox open={true} onClose={onClose} ariaLabel="Preview" children={null} />
|
||||
);
|
||||
rerender(
|
||||
<AttachmentLightbox open={false} onClose={onClose} ariaLabel="Preview" children={null} />
|
||||
);
|
||||
rerender(
|
||||
<AttachmentLightbox open={true} onClose={onClose} ariaLabel="Preview" children={null} />
|
||||
);
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
451
canvas/src/components/tabs/config/__tests__/form-inputs.test.tsx
Normal file
451
canvas/src/components/tabs/config/__tests__/form-inputs.test.tsx
Normal file
@ -0,0 +1,451 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* form-inputs — pure presentational form primitives for the Config tab.
|
||||
*
|
||||
* NOTE: No @testing-library/jest-dom import — use textContent / className /
|
||||
* getAttribute / checked / value checks to avoid "expect is not defined"
|
||||
* errors in this vitest configuration.
|
||||
*
|
||||
* Covers:
|
||||
* - TextInput renders label and input with correct value
|
||||
* - TextInput calls onChange with new value on keystroke
|
||||
* - TextInput renders placeholder text when provided
|
||||
* - TextInput applies mono class when mono=true
|
||||
* - TextInput input has accessible aria-label from label
|
||||
* - TextInput input is not mono by default
|
||||
* - NumberInput renders label and number input
|
||||
* - NumberInput calls onChange with parsed integer on keystroke
|
||||
* - NumberInput calls onChange with 0 for non-numeric input
|
||||
* - NumberInput respects min/max bounds
|
||||
* - NumberInput input has aria-label from label prop
|
||||
* - NumberInput input has font-mono class
|
||||
* - Toggle renders checkbox with label text
|
||||
* - Toggle renders checked/unchecked state correctly
|
||||
* - Toggle calls onChange with boolean on toggle
|
||||
* - TagList renders existing tags with remove buttons
|
||||
* - TagList × button has aria-label "Remove tag {value}"
|
||||
* - TagList calls onChange without removed tag on × click
|
||||
* - TagList renders the label text
|
||||
* - TagList renders placeholder text when provided
|
||||
* - TagList renders exactly one textbox
|
||||
* - TagList adds tag on Enter key
|
||||
* - TagList does not add empty/whitespace-only tags on Enter
|
||||
* - TagList clears input after adding tag
|
||||
* - Section renders the title
|
||||
* - Section renders children when open (defaultOpen=true)
|
||||
* - Section starts closed when defaultOpen=false
|
||||
* - Section opens/closes content on title click
|
||||
* - Section button has aria-expanded reflecting open state
|
||||
* - Section toggle indicator changes on open/close
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import React from "react";
|
||||
|
||||
import {
|
||||
TextInput,
|
||||
NumberInput,
|
||||
Toggle,
|
||||
TagList,
|
||||
Section,
|
||||
} from "../form-inputs";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
// ─── TextInput ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe("TextInput", () => {
|
||||
it("renders the label text", () => {
|
||||
const { container } = render(
|
||||
<TextInput label="Agent Name" value="" onChange={vi.fn()} />,
|
||||
);
|
||||
expect(container.textContent).toContain("Agent Name");
|
||||
});
|
||||
|
||||
it("renders the input with the given value", () => {
|
||||
render(<TextInput label="Model" value="claude-opus-4" onChange={vi.fn()} />);
|
||||
const input = document.querySelector("input") as HTMLInputElement;
|
||||
expect(input.value).toBe("claude-opus-4");
|
||||
});
|
||||
|
||||
it("calls onChange with new value on keystroke", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<TextInput label="Name" value="hello" onChange={onChange} />);
|
||||
const input = document.querySelector("input") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: "hello world" } });
|
||||
expect(onChange).toHaveBeenCalledWith("hello world");
|
||||
});
|
||||
|
||||
it("renders placeholder text when provided", () => {
|
||||
render(
|
||||
<TextInput
|
||||
label="Token"
|
||||
value=""
|
||||
onChange={vi.fn()}
|
||||
placeholder="sk-..."
|
||||
/>,
|
||||
);
|
||||
const input = document.querySelector("input") as HTMLInputElement;
|
||||
expect(input.getAttribute("placeholder")).toBe("sk-...");
|
||||
});
|
||||
|
||||
it("applies mono class when mono=true", () => {
|
||||
const { container } = render(
|
||||
<TextInput label="Model" value="" onChange={vi.fn()} mono />,
|
||||
);
|
||||
const input = container.querySelector("input") as HTMLInputElement;
|
||||
expect(input.className).toContain("font-mono");
|
||||
});
|
||||
|
||||
it("input has aria-label matching the label", () => {
|
||||
render(<TextInput label="API Key" value="" onChange={vi.fn()} />);
|
||||
const input = document.querySelector("input") as HTMLInputElement;
|
||||
expect(input.getAttribute("aria-label")).toBe("API Key");
|
||||
});
|
||||
|
||||
it("input is not mono by default", () => {
|
||||
const { container } = render(
|
||||
<TextInput label="Description" value="" onChange={vi.fn()} />,
|
||||
);
|
||||
const input = container.querySelector("input") as HTMLInputElement;
|
||||
expect(input.className).not.toContain("font-mono");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── NumberInput ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("NumberInput", () => {
|
||||
it("renders the label text", () => {
|
||||
const { container } = render(
|
||||
<NumberInput label="Timeout (s)" value={30} onChange={vi.fn()} />,
|
||||
);
|
||||
expect(container.textContent).toContain("Timeout (s)");
|
||||
});
|
||||
|
||||
it("renders the input with the given numeric value", () => {
|
||||
render(<NumberInput label="Retries" value={3} onChange={vi.fn()} />);
|
||||
const input = document.querySelector("input[type=number]") as HTMLInputElement;
|
||||
expect(input.value).toBe("3");
|
||||
});
|
||||
|
||||
it("calls onChange with parsed integer on keystroke", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<NumberInput label="Delay" value={1} onChange={onChange} />);
|
||||
const input = document.querySelector("input[type=number]") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: "7" } });
|
||||
expect(onChange).toHaveBeenCalledWith(7);
|
||||
});
|
||||
|
||||
it("calls onChange with 0 for non-numeric input", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<NumberInput label="Count" value={5} onChange={onChange} />);
|
||||
const input = document.querySelector("input[type=number]") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: "abc" } });
|
||||
expect(onChange).toHaveBeenCalledWith(0);
|
||||
});
|
||||
|
||||
it("respects min attribute", () => {
|
||||
render(
|
||||
<NumberInput
|
||||
label="Port"
|
||||
value={8000}
|
||||
onChange={vi.fn()}
|
||||
min={1024}
|
||||
/>,
|
||||
);
|
||||
const input = document.querySelector("input[type=number]") as HTMLInputElement;
|
||||
expect(input.getAttribute("min")).toBe("1024");
|
||||
});
|
||||
|
||||
it("respects max attribute", () => {
|
||||
render(
|
||||
<NumberInput
|
||||
label="Memory (MB)"
|
||||
value={256}
|
||||
onChange={vi.fn()}
|
||||
max={65535}
|
||||
/>,
|
||||
);
|
||||
const input = document.querySelector("input[type=number]") as HTMLInputElement;
|
||||
expect(input.getAttribute("max")).toBe("65535");
|
||||
});
|
||||
|
||||
it("input has aria-label from label prop", () => {
|
||||
render(<NumberInput label="Timeout" value={60} onChange={vi.fn()} />);
|
||||
const input = document.querySelector("input[type=number]") as HTMLInputElement;
|
||||
expect(input.getAttribute("aria-label")).toBe("Timeout");
|
||||
});
|
||||
|
||||
it("input has font-mono class", () => {
|
||||
const { container } = render(
|
||||
<NumberInput label="Budget" value={100} onChange={vi.fn()} />,
|
||||
);
|
||||
const input = container.querySelector("input") as HTMLInputElement;
|
||||
expect(input.className).toContain("font-mono");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Toggle ──────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("Toggle", () => {
|
||||
it("renders the checkbox with label text", () => {
|
||||
const { container } = render(
|
||||
<Toggle label="Enable streaming" checked={false} onChange={vi.fn()} />,
|
||||
);
|
||||
const checkbox = container.querySelector(
|
||||
"input[type=checkbox]",
|
||||
) as HTMLInputElement;
|
||||
expect(checkbox.checked).toBe(false);
|
||||
expect(
|
||||
checkbox.closest("label")?.textContent,
|
||||
).toContain("Enable streaming");
|
||||
});
|
||||
|
||||
it("renders checked state correctly", () => {
|
||||
const { container } = render(
|
||||
<Toggle label="Push notifications" checked onChange={vi.fn()} />,
|
||||
);
|
||||
const checkbox = container.querySelector(
|
||||
"input[type=checkbox]",
|
||||
) as HTMLInputElement;
|
||||
expect(checkbox.checked).toBe(true);
|
||||
});
|
||||
|
||||
it("calls onChange with true when toggled on", () => {
|
||||
const onChange = vi.fn();
|
||||
const { container } = render(
|
||||
<Toggle label="Escalate" checked={false} onChange={onChange} />,
|
||||
);
|
||||
const checkbox = container.querySelector(
|
||||
"input[type=checkbox]",
|
||||
) as HTMLInputElement;
|
||||
checkbox.click();
|
||||
expect(onChange).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it("calls onChange with false when toggled off", () => {
|
||||
const onChange = vi.fn();
|
||||
const { container } = render(
|
||||
<Toggle label="Escalate" checked onChange={onChange} />,
|
||||
);
|
||||
const checkbox = container.querySelector(
|
||||
"input[type=checkbox]",
|
||||
) as HTMLInputElement;
|
||||
checkbox.click();
|
||||
expect(onChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it("checkbox is a native input element", () => {
|
||||
const { container } = render(
|
||||
<Toggle label="Feature flag" checked={false} onChange={vi.fn()} />,
|
||||
);
|
||||
expect(container.querySelector("input[type=checkbox]")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── TagList ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("TagList", () => {
|
||||
it("renders existing tags", () => {
|
||||
const { container } = render(
|
||||
<TagList label="Tools" values={["file_read", "bash"]} onChange={vi.fn()} />,
|
||||
);
|
||||
expect(container.textContent).toContain("file_read");
|
||||
expect(container.textContent).toContain("bash");
|
||||
});
|
||||
|
||||
it("renders × remove button for each tag with aria-label", () => {
|
||||
render(
|
||||
<TagList
|
||||
label="Skills"
|
||||
values={["python", "golang"]}
|
||||
onChange={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
const buttons = document.querySelectorAll("button");
|
||||
// buttons[0] = first × (python), buttons[1] = second × (golang)
|
||||
expect(buttons[0].getAttribute("aria-label")).toBe(
|
||||
"Remove tag python",
|
||||
);
|
||||
expect(buttons[1].getAttribute("aria-label")).toBe(
|
||||
"Remove tag golang",
|
||||
);
|
||||
});
|
||||
|
||||
it("calls onChange without removed tag when × is clicked", () => {
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<TagList
|
||||
label="Tags"
|
||||
values={["react", "vue", "angular"]}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
const buttons = document.querySelectorAll("button");
|
||||
// buttons[0] = react ×, buttons[1] = vue ×, buttons[2] = angular ×
|
||||
buttons[0].click(); // Remove react
|
||||
expect(onChange).toHaveBeenCalledWith(["vue", "angular"]);
|
||||
});
|
||||
|
||||
it("renders the label text", () => {
|
||||
const { container } = render(
|
||||
<TagList label="Required env vars" values={[]} onChange={vi.fn()} />,
|
||||
);
|
||||
expect(container.textContent).toContain("Required env vars");
|
||||
});
|
||||
|
||||
it("renders placeholder text when provided", () => {
|
||||
render(
|
||||
<TagList
|
||||
label="Tags"
|
||||
values={[]}
|
||||
onChange={vi.fn()}
|
||||
placeholder="Add a tag..."
|
||||
/>,
|
||||
);
|
||||
const input = document.querySelector("input[type=text]") as HTMLInputElement;
|
||||
expect(input.getAttribute("placeholder")).toBe("Add a tag...");
|
||||
});
|
||||
|
||||
it("renders exactly one textbox (the input)", () => {
|
||||
const { container } = render(
|
||||
<TagList
|
||||
label="Tools"
|
||||
values={["read", "write"]}
|
||||
onChange={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(
|
||||
container.querySelectorAll("input[type=text]"),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("adds tag on Enter key", () => {
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<TagList label="Skills" values={["python"]} onChange={onChange} />,
|
||||
);
|
||||
const input = document.querySelector("input[type=text]") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: "rust" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(onChange).toHaveBeenCalledWith(["python", "rust"]);
|
||||
});
|
||||
|
||||
it("does not add empty tag on Enter", () => {
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<TagList label="Tools" values={[]} onChange={onChange} />,
|
||||
);
|
||||
const input = document.querySelector("input[type=text]") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: " " } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clears input after adding tag", () => {
|
||||
render(
|
||||
<TagList label="Tags" values={[]} onChange={vi.fn()} />,
|
||||
);
|
||||
const input = document.querySelector("input[type=text]") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: "golang" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(input.value).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Section ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe("Section", () => {
|
||||
it("renders the title", () => {
|
||||
const { container } = render(
|
||||
<Section title="Runtime config">Content here</Section>,
|
||||
);
|
||||
expect(container.textContent).toContain("Runtime config");
|
||||
});
|
||||
|
||||
it("renders children when open (defaultOpen=true)", () => {
|
||||
const { container } = render(
|
||||
<Section title="A section">Hidden content</Section>,
|
||||
);
|
||||
expect(container.textContent).toContain("Hidden content");
|
||||
});
|
||||
|
||||
it("starts closed when defaultOpen=false", () => {
|
||||
const { container } = render(
|
||||
<Section title="Collapsed" defaultOpen={false}>
|
||||
Should not be visible
|
||||
</Section>,
|
||||
);
|
||||
expect(container.textContent).not.toContain("Should not be visible");
|
||||
});
|
||||
|
||||
it("opens/closes content on title click", () => {
|
||||
const { container } = render(
|
||||
<Section title="Toggle me" defaultOpen={false}>
|
||||
Now you see me
|
||||
</Section>,
|
||||
);
|
||||
// Should be closed initially
|
||||
expect(container.textContent).not.toContain("Now you see me");
|
||||
// Click to open
|
||||
const btn = container.querySelector("button") as HTMLButtonElement;
|
||||
fireEvent.click(btn);
|
||||
expect(container.textContent).toContain("Now you see me");
|
||||
// Click to close
|
||||
fireEvent.click(btn);
|
||||
expect(container.textContent).not.toContain("Now you see me");
|
||||
});
|
||||
|
||||
it("title button has aria-expanded reflecting open state", () => {
|
||||
// Open section
|
||||
const { container: openContainer } = render(
|
||||
<Section title="A section" defaultOpen={true}>
|
||||
Open content
|
||||
</Section>,
|
||||
);
|
||||
const openBtn = openContainer.querySelector(
|
||||
"button",
|
||||
) as HTMLButtonElement;
|
||||
expect(openBtn.getAttribute("aria-expanded")).toBe("true");
|
||||
|
||||
// Closed section
|
||||
const { container: closedContainer } = render(
|
||||
<Section title="B section" defaultOpen={false}>
|
||||
Closed content
|
||||
</Section>,
|
||||
);
|
||||
const closedBtn = closedContainer.querySelector(
|
||||
"button",
|
||||
) as HTMLButtonElement;
|
||||
expect(closedBtn.getAttribute("aria-expanded")).toBe("false");
|
||||
});
|
||||
|
||||
it("toggle indicator changes between ▾ (open) and ▸ (closed)", () => {
|
||||
// Open: uses ▾
|
||||
const { container: openContainer } = render(
|
||||
<Section title="Indicator" defaultOpen={true}>
|
||||
Open
|
||||
</Section>,
|
||||
);
|
||||
// Button has two spans: title (first) and indicator (second, aria-hidden)
|
||||
const openSpans = openContainer
|
||||
.querySelectorAll("button span");
|
||||
const openIndicator = openSpans[1]?.textContent?.trim();
|
||||
expect(openIndicator).toBe("▾");
|
||||
|
||||
// Closed: uses ▸
|
||||
const { container: closedContainer } = render(
|
||||
<Section title="Indicator" defaultOpen={false}>
|
||||
Closed
|
||||
</Section>,
|
||||
);
|
||||
const closedSpans = closedContainer
|
||||
.querySelectorAll("button span");
|
||||
const closedIndicator = closedSpans[1]?.textContent?.trim();
|
||||
expect(closedIndicator).toBe("▸");
|
||||
});
|
||||
});
|
||||
@ -127,13 +127,21 @@ export function TagList({ label, values, onChange, placeholder }: { label: strin
|
||||
|
||||
export function Section({ title, children, defaultOpen = true }: { title: string; children: React.ReactNode; defaultOpen?: boolean }) {
|
||||
const [open, setOpen] = useState(defaultOpen);
|
||||
// Stable id for aria-controls linkage
|
||||
const id = `section-content-${title.toLowerCase().replace(/\s+/g, "-")}`;
|
||||
return (
|
||||
<div className="border border-line rounded mb-2">
|
||||
<button type="button" onClick={() => setOpen(!open)} className="w-full flex items-center justify-between px-3 py-1.5 text-[10px] text-ink-mid hover:text-ink bg-surface-sunken/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(!open)}
|
||||
aria-expanded={open}
|
||||
aria-controls={id}
|
||||
className="w-full flex items-center justify-between px-3 py-1.5 text-[10px] text-ink-mid hover:text-ink bg-surface-sunken/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-1"
|
||||
>
|
||||
<span className="font-medium uppercase tracking-wider">{title}</span>
|
||||
<span>{open ? "▾" : "▸"}</span>
|
||||
<span aria-hidden="true">{open ? "▾" : "▸"}</span>
|
||||
</button>
|
||||
{open && <div className="p-3 space-y-3">{children}</div>}
|
||||
{open && <div id={id} className="p-3 space-y-3">{children}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
142
canvas/src/components/ui/__tests__/KeyValueField.test.tsx
Normal file
142
canvas/src/components/ui/__tests__/KeyValueField.test.tsx
Normal file
@ -0,0 +1,142 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Tests for KeyValueField component.
|
||||
*
|
||||
* Covers: initial password type, onChange callback (including whitespace trim
|
||||
* on type), aria-label forwarding, disabled state, and auto-hide timer setup.
|
||||
*/
|
||||
import React from "react";
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import { render, screen, fireEvent, cleanup, act } from "@testing-library/react";
|
||||
import { KeyValueField } from "../KeyValueField";
|
||||
|
||||
describe("KeyValueField — rendering", () => {
|
||||
afterEach(cleanup);
|
||||
|
||||
it("renders input with type=password by default (secret hidden)", () => {
|
||||
render(<KeyValueField value="" onChange={vi.fn()} />);
|
||||
const input = screen.getByLabelText("Secret value");
|
||||
expect(input.getAttribute("type")).toBe("password");
|
||||
});
|
||||
|
||||
it("passes custom aria-label to the input element", () => {
|
||||
render(<KeyValueField value="" onChange={vi.fn()} aria-label="API secret key" />);
|
||||
expect(screen.getByLabelText("API secret key")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("disables the input when disabled=true", () => {
|
||||
render(<KeyValueField value="secret" onChange={vi.fn()} disabled />);
|
||||
expect(screen.getByLabelText("Secret value").disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("renders with the current value", () => {
|
||||
render(<KeyValueField value="sk-test-key-123" onChange={vi.fn()} />);
|
||||
expect(screen.getByLabelText("Secret value").value).toBe("sk-test-key-123");
|
||||
});
|
||||
|
||||
it("renders with the placeholder text", () => {
|
||||
render(<KeyValueField value="" onChange={vi.fn()} placeholder="Enter API key" />);
|
||||
expect(screen.getByLabelText("Secret value").getAttribute("placeholder")).toBe("Enter API key");
|
||||
});
|
||||
|
||||
it("renders the RevealToggle child button", () => {
|
||||
render(<KeyValueField value="secret" onChange={vi.fn()} />);
|
||||
// KeyValueField renders exactly one button (the RevealToggle)
|
||||
expect(screen.getByRole("button")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("KeyValueField — onChange", () => {
|
||||
afterEach(cleanup);
|
||||
|
||||
it("calls onChange with the new value when user types", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<KeyValueField value="" onChange={onChange} />);
|
||||
fireEvent.change(screen.getByLabelText("Secret value"), { target: { value: "new-value" } });
|
||||
expect(onChange).toHaveBeenCalledWith("new-value");
|
||||
});
|
||||
|
||||
it("trims leading whitespace when user types with leading space", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<KeyValueField value="" onChange={onChange} />);
|
||||
fireEvent.change(screen.getByLabelText("Secret value"), { target: { value: " trimmed" } });
|
||||
expect(onChange).toHaveBeenCalledWith("trimmed");
|
||||
});
|
||||
|
||||
it("trims trailing whitespace when user types with trailing space", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<KeyValueField value="" onChange={onChange} />);
|
||||
fireEvent.change(screen.getByLabelText("Secret value"), { target: { value: "trimmed " } });
|
||||
expect(onChange).toHaveBeenCalledWith("trimmed");
|
||||
});
|
||||
|
||||
it("trims both sides when user types whitespace-surrounded value", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<KeyValueField value="" onChange={onChange} />);
|
||||
fireEvent.change(screen.getByLabelText("Secret value"), { target: { value: " both sides " } });
|
||||
expect(onChange).toHaveBeenCalledWith("both sides");
|
||||
});
|
||||
|
||||
it("does not modify value with no whitespace", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<KeyValueField value="" onChange={onChange} />);
|
||||
fireEvent.change(screen.getByLabelText("Secret value"), { target: { value: "clean-value" } });
|
||||
expect(onChange).toHaveBeenCalledWith("clean-value");
|
||||
});
|
||||
});
|
||||
|
||||
describe("KeyValueField — auto-hide timer setup", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("sets up a 30s setTimeout when the component mounts with a non-empty value", () => {
|
||||
const setTimeoutSpy = vi.spyOn(global, "setTimeout");
|
||||
render(<KeyValueField value="secret" onChange={vi.fn()} />);
|
||||
// No timer should be set initially (revealed=false by default)
|
||||
const callsBeforeInteraction = setTimeoutSpy.mock.calls.length;
|
||||
|
||||
// Simulate reveal (click the only button)
|
||||
act(() => { fireEvent.click(screen.getByRole("button")); });
|
||||
|
||||
// After reveal, a 30s timer should be set
|
||||
const timerCalls = setTimeoutSpy.mock.calls.filter(
|
||||
([, delay]) => delay === 30_000,
|
||||
);
|
||||
expect(timerCalls.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("clears existing timer when a new toggle happens before auto-hide fires", () => {
|
||||
const clearTimeoutSpy = vi.spyOn(global, "clearTimeout");
|
||||
const timerObj = {}; // fake timer ID
|
||||
vi.spyOn(global, "setTimeout").mockImplementation((fn: () => void, delay: number) => {
|
||||
return timerObj;
|
||||
});
|
||||
render(<KeyValueField value="secret" onChange={vi.fn()} />);
|
||||
|
||||
// First toggle — reveal
|
||||
act(() => { fireEvent.click(screen.getByRole("button")); });
|
||||
|
||||
// Second toggle — hide (should clear the timer from first toggle)
|
||||
act(() => { fireEvent.click(screen.getByRole("button")); });
|
||||
|
||||
// clearTimeout was called with the timer object
|
||||
expect(clearTimeoutSpy).toHaveBeenCalledWith(timerObj);
|
||||
});
|
||||
|
||||
it("clears timer on unmount", () => {
|
||||
const clearTimeoutSpy = vi.spyOn(global, "clearTimeout");
|
||||
const { unmount } = render(<KeyValueField value="secret" onChange={vi.fn()} />);
|
||||
|
||||
// Toggle reveal to start the timer
|
||||
act(() => { fireEvent.click(screen.getByRole("button")); });
|
||||
|
||||
unmount();
|
||||
expect(clearTimeoutSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
68
canvas/src/components/ui/__tests__/RevealToggle.test.tsx
Normal file
68
canvas/src/components/ui/__tests__/RevealToggle.test.tsx
Normal file
@ -0,0 +1,68 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Tests for RevealToggle component.
|
||||
*
|
||||
* Covers: eye-icon (hidden) vs eye-off-icon (revealed), onToggle callback,
|
||||
* aria-label (default + custom), title attribute.
|
||||
*/
|
||||
import { afterEach, describe, it, expect, vi } from "vitest";
|
||||
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
|
||||
import { RevealToggle } from "../RevealToggle";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("RevealToggle", () => {
|
||||
it("renders as a button", () => {
|
||||
render(<RevealToggle revealed={false} onToggle={vi.fn()} />);
|
||||
expect(screen.getByRole("button")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("uses default aria-label when not provided", () => {
|
||||
render(<RevealToggle revealed={false} onToggle={vi.fn()} />);
|
||||
expect(screen.getByRole("button").getAttribute("aria-label")).toBe("Toggle reveal secret");
|
||||
});
|
||||
|
||||
it("uses custom aria-label when provided", () => {
|
||||
render(<RevealToggle revealed={false} onToggle={vi.fn()} label="Show password" />);
|
||||
expect(screen.getByRole("button").getAttribute("aria-label")).toBe("Show password");
|
||||
});
|
||||
|
||||
it('title is "Hide value" when revealed', () => {
|
||||
render(<RevealToggle revealed={true} onToggle={vi.fn()} />);
|
||||
expect(screen.getByRole("button").getAttribute("title")).toBe("Hide value");
|
||||
});
|
||||
|
||||
it('title is "Show value" when hidden', () => {
|
||||
render(<RevealToggle revealed={false} onToggle={vi.fn()} />);
|
||||
expect(screen.getByRole("button").getAttribute("title")).toBe("Show value");
|
||||
});
|
||||
|
||||
it("calls onToggle when clicked (revealed=true → should hide)", () => {
|
||||
const onToggle = vi.fn();
|
||||
render(<RevealToggle revealed={true} onToggle={onToggle} />);
|
||||
fireEvent.click(screen.getByRole("button"));
|
||||
expect(onToggle).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("calls onToggle when clicked (revealed=false → should show)", () => {
|
||||
const onToggle = vi.fn();
|
||||
render(<RevealToggle revealed={false} onToggle={onToggle} />);
|
||||
fireEvent.click(screen.getByRole("button"));
|
||||
expect(onToggle).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("renders the eye-open SVG (hide icon) when revealed=false", () => {
|
||||
render(<RevealToggle revealed={false} onToggle={vi.fn()} />);
|
||||
const btn = screen.getByRole("button");
|
||||
// The eye SVG contains a circle element; eye-off has a strikethrough line
|
||||
expect(btn.querySelector("circle")).toBeTruthy();
|
||||
expect(btn.querySelectorAll("line")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("renders the eye-off SVG (show icon) when revealed=true", () => {
|
||||
render(<RevealToggle revealed={true} onToggle={vi.fn()} />);
|
||||
const btn = screen.getByRole("button");
|
||||
// EyeOffIcon has a line (strikethrough) through the eye
|
||||
expect(btn.querySelectorAll("line")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
49
canvas/src/components/ui/__tests__/ValidationHint.test.tsx
Normal file
49
canvas/src/components/ui/__tests__/ValidationHint.test.tsx
Normal file
@ -0,0 +1,49 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Tests for ValidationHint component.
|
||||
*
|
||||
* Covers: null/neutral render, error state (red ⚠ + message), valid state
|
||||
* (green ✓ + "Valid format"), ARIA role="alert" on error.
|
||||
*/
|
||||
import { afterEach, describe, it, expect } from "vitest";
|
||||
import { render, screen, cleanup } from "@testing-library/react";
|
||||
import { ValidationHint } from "../ValidationHint";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("ValidationHint", () => {
|
||||
it("renders nothing when error is null and showValid is false", () => {
|
||||
const { container } = render(<ValidationHint error={null} showValid={false} />);
|
||||
expect(container.innerHTML).toBe("");
|
||||
});
|
||||
|
||||
it("renders nothing when error is null and showValid is undefined", () => {
|
||||
const { container } = render(<ValidationHint error={null} />);
|
||||
expect(container.innerHTML).toBe("");
|
||||
});
|
||||
|
||||
it("renders error state with ⚠ icon and message", () => {
|
||||
render(<ValidationHint error="Key name must be UPPER_SNAKE_CASE" />);
|
||||
const el = screen.getByRole("alert");
|
||||
expect(el.textContent).toContain("⚠");
|
||||
expect(el.textContent).toContain("Key name must be UPPER_SNAKE_CASE");
|
||||
});
|
||||
|
||||
it("renders valid state with ✓ and 'Valid format'", () => {
|
||||
render(<ValidationHint error={null} showValid />);
|
||||
const el = screen.getByText("Valid format");
|
||||
expect(el.textContent).toContain("✓");
|
||||
});
|
||||
|
||||
it("prefers error over valid when both are set (error is not null)", () => {
|
||||
// ValidationHint checks error first; showValid is only rendered when error is falsy.
|
||||
render(<ValidationHint error="Some error" showValid />);
|
||||
expect(screen.getByRole("alert")).toBeTruthy();
|
||||
expect(screen.queryByText("Valid format")).toBeNull();
|
||||
});
|
||||
|
||||
it("error alert has role='alert' for screen readers", () => {
|
||||
render(<ValidationHint error="Invalid format" />);
|
||||
expect(screen.getByRole("alert")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user