Files
fusion/packages/dashboard/app/context/__tests__/NodeContext.test.tsx
gsxdsm 3031d05a68 fix(dashboard): clear all 661 test-file type errors
Production typecheck (tsconfig.json + tsconfig.app.json) was already
clean, but a third config that includes test files surfaced 661 errors
across 60+ test files — accumulated drift between mock fixtures and
production types. Six parallel typescript-pro agents fixed every one
without touching production code.

Per-scope before/after (errors → 0):
  ChatView                                                     183
  Mailbox + Agent suite (5 files)                              156
  Task / Modal suite (6 files)                                 127
  App + small components (12 files)                             96
  Hooks + api/auth (8 files)                                    48
  Long tail (32 files)                                          51
  -----------------------------------------------------------------
  Total                                                        661

Major fix categories:
- Untyped state objects inferring `never[]` / `null` literals (root
  cause of ~120 errors in ChatView alone — added a single
  `UseChatReturn` annotation)
- Mock objects missing fields that became required: `WorkflowStep.mode`,
  `ChatMessage.thinkingOutput / metadata`, `ChatSession.projectId`,
  `Task.log`, `ProjectHealth` fields, `PtyTerminalSessionInfo.createdAt`,
  `Agent.metadata`, `InboxResponse.total`, etc.
- Mock objects with stale fields that no longer exist:
  `AgentBudgetStatus.budgetPeriod`, `truncated` on log responses,
  `OutboxResponse.unreadCount`, `MergeResult.source/target/details`
- Modal props that became required (e.g. `PlanningModeModal.onTasksCreated`)
- String literals not in narrowed unions (`Column`, `WorkflowStepPhase`,
  `InsightStatus`, `AgentLogType`, etc.)
- `querySelector` returning `Element` cast to `HTMLElement` for
  `@testing-library/react`'s `within()`
- Vitest mock typing: `.mock.calls` access needing `vi.mocked(...)`,
  zero-param tuple handling, generic `vi.fn(() => [])` inferring
  `never[]`

Helpers introduced in test files (no shared infra):
- `makeSettings(overrides)` in ModelSelectorTab.test.tsx
- `makePromptOverrides(overrides)` in AgentPromptsManager.test.tsx
- `FileBrowserTestOverrides` type alias in FileBrowser.test.tsx
- `makeInboxResponse / makeOutboxResponse` in MailboxView.test.tsx

Verification:
- tsc -p tsconfig.json:        exit 0
- tsc -p tsconfig.app.json:    exit 0
- tsc -p tsconfig.test-check.json (new — includes test files): exit 0
- vitest run:                  9639 / 9641 (2 pre-existing failures
                               in terminal-mobile-keyboard-layout.test.ts
                               unrelated to this work; verified via
                               `git stash` + run on clean HEAD)

Adds packages/dashboard/tsconfig.test-check.json to keep this regression
guard available locally — same as tsconfig.app.json minus the test
exclude.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 19:59:52 -07:00

211 lines
6.3 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { renderHook, waitFor, act } from "@testing-library/react";
import { NodeProvider, useNodeContext } from "../NodeContext";
import type { NodeConfig } from "@fusion/core";
// Mock the API functions
vi.mock("../../api", () => ({
fetchGlobalSettings: vi.fn(),
updateGlobalSettings: vi.fn(),
}));
import { fetchGlobalSettings, updateGlobalSettings } from "../../api";
const mockRemoteNode: NodeConfig = {
id: "node-remote-1",
name: "Remote Node",
type: "remote",
url: "https://remote.example.com",
apiKey: "test-key",
status: "online",
maxConcurrent: 4,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
};
describe("NodeContext", () => {
beforeEach(() => {
localStorage.clear();
vi.clearAllMocks();
// Default mock implementations
(fetchGlobalSettings as ReturnType<typeof vi.fn>).mockResolvedValue({});
(updateGlobalSettings as ReturnType<typeof vi.fn>).mockResolvedValue({});
});
afterEach(() => {
localStorage.clear();
});
function renderWithProvider() {
return renderHook(() => useNodeContext(), {
wrapper: ({ children }) => <NodeProvider>{children}</NodeProvider>,
});
}
it("initializes with null currentNode when no saved node", async () => {
const { result } = renderWithProvider();
await waitFor(() => {
expect(result.current.currentNode).toBeNull();
});
expect(result.current.currentNodeId).toBeNull();
expect(result.current.isRemote).toBe(false);
});
it("loads saved node ID from global settings", async () => {
(fetchGlobalSettings as ReturnType<typeof vi.fn>).mockResolvedValue({
dashboardCurrentNodeId: "node-remote-1",
});
const { result } = renderWithProvider();
// Should have loaded the node ID from global settings
// Note: currentNode stays null until App.tsx resolves it from nodes list
await waitFor(() => {
expect(fetchGlobalSettings).toHaveBeenCalled();
});
// The NodeContext only stores the ID; App.tsx resolves the full node
// We verify the settings were fetched correctly
expect(result.current.currentNode).toBeNull();
});
it("persists node selection to global settings", async () => {
const { result } = renderWithProvider();
await waitFor(() => {
expect(result.current.currentNode).toBeNull();
});
act(() => {
result.current.setCurrentNode(mockRemoteNode);
});
expect(result.current.currentNode).toEqual(mockRemoteNode);
expect(result.current.currentNodeId).toBe("node-remote-1");
expect(result.current.isRemote).toBe(true);
// Should persist to global settings
expect(updateGlobalSettings).toHaveBeenCalledWith({
dashboardCurrentNodeId: "node-remote-1",
});
});
it("clears node selection and updates global settings", async () => {
// Start with a saved node
(fetchGlobalSettings as ReturnType<typeof vi.fn>).mockResolvedValue({
dashboardCurrentNodeId: "node-remote-1",
});
const { result } = renderWithProvider();
await waitFor(() => {
expect(fetchGlobalSettings).toHaveBeenCalled();
});
// Simulate App.tsx resolving the node from nodes list
act(() => {
result.current.setCurrentNode(mockRemoteNode);
});
expect(result.current.currentNode).toEqual(mockRemoteNode);
// Clear the selection
act(() => {
result.current.clearCurrentNode();
});
expect(result.current.currentNode).toBeNull();
expect(result.current.currentNodeId).toBeNull();
expect(result.current.isRemote).toBe(false);
// Should persist the clear to global settings
expect(updateGlobalSettings).toHaveBeenLastCalledWith({
dashboardCurrentNodeId: undefined,
});
});
it("handles global settings fetch failure gracefully", async () => {
(fetchGlobalSettings as ReturnType<typeof vi.fn>).mockRejectedValue(new Error("Network error"));
const { result } = renderWithProvider();
await waitFor(() => {
expect(result.current.currentNode).toBeNull();
});
// Should still be usable even when settings fetch fails
act(() => {
result.current.setCurrentNode(mockRemoteNode);
});
expect(result.current.currentNode).toEqual(mockRemoteNode);
expect(result.current.isRemote).toBe(true);
});
it("handles global settings update failure gracefully", async () => {
(updateGlobalSettings as ReturnType<typeof vi.fn>).mockRejectedValue(new Error("Network error"));
const { result } = renderWithProvider();
await waitFor(() => {
expect(result.current.currentNode).toBeNull();
});
// Should still update state even if persistence fails
act(() => {
result.current.setCurrentNode(mockRemoteNode);
});
expect(result.current.currentNode).toEqual(mockRemoteNode);
});
it("migrates legacy localStorage to global settings", async () => {
// Set up legacy localStorage
localStorage.setItem("fusion-dashboard-current-node", JSON.stringify(mockRemoteNode));
(fetchGlobalSettings as ReturnType<typeof vi.fn>).mockResolvedValue({});
const { result } = renderWithProvider();
await waitFor(() => {
expect(fetchGlobalSettings).toHaveBeenCalled();
});
// Should migrate to global settings
expect(updateGlobalSettings).toHaveBeenCalledWith({
dashboardCurrentNodeId: "node-remote-1",
});
});
it("does not migrate local node from legacy localStorage", async () => {
// localStorage stores remote nodes only; local is represented by null
const { result } = renderWithProvider();
await waitFor(() => {
expect(fetchGlobalSettings).toHaveBeenCalled();
});
// Should not persist any changes when on local node
act(() => {
result.current.clearCurrentNode();
});
// Should clear from global settings
expect(updateGlobalSettings).toHaveBeenCalledWith({
dashboardCurrentNodeId: undefined,
});
});
it("throws error when useNodeContext is used outside NodeProvider", () => {
// Suppress console.error for this test
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
expect(() => {
renderHook(() => useNodeContext());
}).toThrow("useNodeContext must be used within a NodeProvider");
consoleSpy.mockRestore();
});
});