Files
cc-switch/tests/components/McpFormModal.test.tsx

427 lines
13 KiB
TypeScript
Raw Permalink Normal View History

test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
import React from "react";
test: extend MCP UI test coverage with wizard, TOML, and error handling ## McpFormModal Component Tests (+5 tests) ### Infrastructure Improvements - Enhance McpWizardModal mock from null to functional mock with testable onApply callback - Refactor renderForm helper to support custom onSave/onClose mock injection - Add McpServer type import for type-safe test data ### New Test Cases 1. **Wizard Integration**: Verify wizard generates config and auto-fills ID + JSON fields - Click "Use Wizard" → Apply → Form fields populated with wizard-id and config - Uses act() wrapper for React 18 async state updates 2. **TOML Auto-extraction (Codex)**: Test TOML → JSON conversion with ID extraction - Parse `[mcp.servers.demo]` → auto-fill ID as "demo" - Verify server object correctly parsed from TOML format - Codex-specific feature for config.toml compatibility 3. **TOML Validation Error**: Test missing required field handling - TOML with type="stdio" but no command → block submit - Display localized error toast: mcp.error.idRequired (3s duration) 4. **Edit Mode Immutability**: Verify ID field disabled during edit - ID input has disabled attribute and keeps original value - Config updates applied while enabled state preserved - syncOtherSide defaults to false in edit mode 5. **Error Recovery**: Test save failure button state restoration - Inject failing onSave mock → trigger error - Verify toast error displays translated message - Submit button disabled state resets to false for retry ## useMcpActions Hook Tests (+2 tests) ### New API Mocks - Add syncEnabledToClaude and syncEnabledToCodex mock functions ### New Test Cases 1. **Backend Error Message Mapping**: Map Chinese error to i18n key - Backend: "stdio 类型的 MCP 服务器必须包含 command 字段" - Frontend: mcp.error.commandRequired (6s toast duration) 2. **Cross-app Sync Logic**: Verify conditional sync behavior - claude → claude: setEnabled called, syncEnabledToClaude NOT called - Validates sync only occurs when crossing app types ## Minor Changes - McpPanel.test.tsx: Add trailing newline (formatter compliance) ## Test Coverage - Test files: 17 (unchanged) - Total tests: 112 → 119 (+7, +6.3%) - Execution time: 3.20s - All 119 tests passing ✅
2025-10-26 15:03:05 +08:00
import { render, screen, fireEvent, waitFor, act } from "@testing-library/react";
import type { McpServer } from "@/types";
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
import McpFormModal from "@/components/mcp/McpFormModal";
const toastErrorMock = vi.hoisted(() => vi.fn());
const toastSuccessMock = vi.hoisted(() => vi.fn());
const upsertMock = vi.hoisted(() => {
const fn = vi.fn();
fn.mockResolvedValue(undefined);
return fn;
});
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
vi.mock("sonner", () => ({
toast: {
error: (...args: unknown[]) => toastErrorMock(...args),
success: (...args: unknown[]) => toastSuccessMock(...args),
},
}));
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, params?: Record<string, unknown>) =>
params ? `${key}:${JSON.stringify(params)}` : key,
}),
refactor: migrate all Tauri commands to camelCase parameters This commit addresses parameter naming inconsistencies caused by Tauri v2's requirement for camelCase parameter names in IPC commands. Backend changes (Rust): - Updated all command parameters from snake_case to camelCase - Commands affected: * provider.rs: providerId (×4), timeoutSecs * import_export.rs: filePath (×2), defaultName * config.rs: defaultPath - Added #[allow(non_snake_case)] attributes for camelCase parameters - Removed unused QueryUsageParams struct Frontend changes (TypeScript): - Removed redundant snake_case parameters from all invoke() calls - Updated API files: * usage.ts: removed debug logs, unified to providerId * vscode.ts: updated 8 functions (providerId, timeoutSecs, filePath, defaultName) * settings.ts: updated 4 functions (defaultPath, filePath, defaultName) - Ensured all parameters now use camelCase exclusively Test updates: - Updated MSW handlers to accept both old and new parameter formats during transition - Added i18n mock compatibility for tests Root cause: The issue stemmed from Tauri v2 strictly requiring camelCase for command parameters, while the codebase was using snake_case. This caused parameters like 'provider_id' to not be recognized by the backend, resulting in "missing providerId parameter" errors. BREAKING CHANGE: All Tauri command invocations now require camelCase parameters. Any external tools or scripts calling these commands must be updated accordingly. Fixes: Usage query always failing with "missing providerId" error Fixes: Custom endpoint management not receiving provider ID Fixes: Import/export dialogs not respecting default paths
2025-11-03 16:50:23 +08:00
// 提供 initReactI18next 以兼容 i18n 初始化路径
initReactI18next: { type: "3rdParty", init: () => {} },
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
}));
vi.mock("@/config/mcpPresets", () => ({
mcpPresets: [
{
id: "preset-stdio",
server: { type: "stdio", command: "preset-cmd" },
},
],
getMcpPresetWithDescription: (preset: any) => ({
...preset,
description: "Preset description",
tags: ["preset"],
}),
}));
vi.mock("@/components/ui/button", () => ({
Button: ({ children, onClick, type = "button", ...rest }: any) => (
<button type={type} onClick={onClick} {...rest}>
{children}
</button>
),
}));
vi.mock("@/components/ui/input", () => ({
Input: ({ value, onChange, ...rest }: any) => (
<input
value={value}
onChange={(event) => onChange?.({ target: { value: event.target.value } })}
{...rest}
/>
),
}));
vi.mock("@/components/ui/textarea", () => ({
Textarea: ({ value, onChange, ...rest }: any) => (
<textarea
value={value}
onChange={(event) => onChange?.({ target: { value: event.target.value } })}
{...rest}
/>
),
}));
vi.mock("@/components/ui/checkbox", () => ({
Checkbox: ({ id, checked, onCheckedChange, ...rest }: any) => (
<input
type="checkbox"
id={id}
checked={checked ?? false}
onChange={(e) => onCheckedChange?.(e.target.checked)}
{...rest}
/>
),
}));
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
vi.mock("@/components/ui/dialog", () => ({
Dialog: ({ children }: any) => <div>{children}</div>,
DialogContent: ({ children }: any) => <div>{children}</div>,
DialogHeader: ({ children }: any) => <div>{children}</div>,
DialogTitle: ({ children }: any) => <div>{children}</div>,
DialogFooter: ({ children }: any) => <div>{children}</div>,
}));
vi.mock("@/components/mcp/McpWizardModal", () => ({
test: extend MCP UI test coverage with wizard, TOML, and error handling ## McpFormModal Component Tests (+5 tests) ### Infrastructure Improvements - Enhance McpWizardModal mock from null to functional mock with testable onApply callback - Refactor renderForm helper to support custom onSave/onClose mock injection - Add McpServer type import for type-safe test data ### New Test Cases 1. **Wizard Integration**: Verify wizard generates config and auto-fills ID + JSON fields - Click "Use Wizard" → Apply → Form fields populated with wizard-id and config - Uses act() wrapper for React 18 async state updates 2. **TOML Auto-extraction (Codex)**: Test TOML → JSON conversion with ID extraction - Parse `[mcp.servers.demo]` → auto-fill ID as "demo" - Verify server object correctly parsed from TOML format - Codex-specific feature for config.toml compatibility 3. **TOML Validation Error**: Test missing required field handling - TOML with type="stdio" but no command → block submit - Display localized error toast: mcp.error.idRequired (3s duration) 4. **Edit Mode Immutability**: Verify ID field disabled during edit - ID input has disabled attribute and keeps original value - Config updates applied while enabled state preserved - syncOtherSide defaults to false in edit mode 5. **Error Recovery**: Test save failure button state restoration - Inject failing onSave mock → trigger error - Verify toast error displays translated message - Submit button disabled state resets to false for retry ## useMcpActions Hook Tests (+2 tests) ### New API Mocks - Add syncEnabledToClaude and syncEnabledToCodex mock functions ### New Test Cases 1. **Backend Error Message Mapping**: Map Chinese error to i18n key - Backend: "stdio 类型的 MCP 服务器必须包含 command 字段" - Frontend: mcp.error.commandRequired (6s toast duration) 2. **Cross-app Sync Logic**: Verify conditional sync behavior - claude → claude: setEnabled called, syncEnabledToClaude NOT called - Validates sync only occurs when crossing app types ## Minor Changes - McpPanel.test.tsx: Add trailing newline (formatter compliance) ## Test Coverage - Test files: 17 (unchanged) - Total tests: 112 → 119 (+7, +6.3%) - Execution time: 3.20s - All 119 tests passing ✅
2025-10-26 15:03:05 +08:00
default: ({ isOpen, onApply }: any) =>
isOpen ? (
<button
type="button"
data-testid="wizard-apply"
onClick={() =>
onApply(
"wizard-id",
JSON.stringify({ type: "stdio", command: "wizard-cmd" }),
)
}
>
wizard-apply
</button>
) : null,
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
}));
vi.mock("@/hooks/useMcp", async () => {
const actual = await vi.importActual<typeof import("@/hooks/useMcp")>(
"@/hooks/useMcp",
);
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
return {
...actual,
useUpsertMcpServer: () => ({
mutateAsync: (...args: unknown[]) => upsertMock(...args),
}),
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
};
});
describe("McpFormModal", () => {
beforeEach(() => {
toastErrorMock.mockClear();
toastSuccessMock.mockClear();
upsertMock.mockClear();
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
});
const renderForm = (
props?: Partial<React.ComponentProps<typeof McpFormModal>>,
) => {
const { onSave: overrideOnSave, onClose: overrideOnClose, ...rest } =
props ?? {};
const onSave = overrideOnSave ?? vi.fn().mockResolvedValue(undefined);
const onClose = overrideOnClose ?? vi.fn();
render(
<McpFormModal
onSave={onSave}
onClose={onClose}
existingIds={[]}
defaultFormat="json"
test: extend MCP UI test coverage with wizard, TOML, and error handling ## McpFormModal Component Tests (+5 tests) ### Infrastructure Improvements - Enhance McpWizardModal mock from null to functional mock with testable onApply callback - Refactor renderForm helper to support custom onSave/onClose mock injection - Add McpServer type import for type-safe test data ### New Test Cases 1. **Wizard Integration**: Verify wizard generates config and auto-fills ID + JSON fields - Click "Use Wizard" → Apply → Form fields populated with wizard-id and config - Uses act() wrapper for React 18 async state updates 2. **TOML Auto-extraction (Codex)**: Test TOML → JSON conversion with ID extraction - Parse `[mcp.servers.demo]` → auto-fill ID as "demo" - Verify server object correctly parsed from TOML format - Codex-specific feature for config.toml compatibility 3. **TOML Validation Error**: Test missing required field handling - TOML with type="stdio" but no command → block submit - Display localized error toast: mcp.error.idRequired (3s duration) 4. **Edit Mode Immutability**: Verify ID field disabled during edit - ID input has disabled attribute and keeps original value - Config updates applied while enabled state preserved - syncOtherSide defaults to false in edit mode 5. **Error Recovery**: Test save failure button state restoration - Inject failing onSave mock → trigger error - Verify toast error displays translated message - Submit button disabled state resets to false for retry ## useMcpActions Hook Tests (+2 tests) ### New API Mocks - Add syncEnabledToClaude and syncEnabledToCodex mock functions ### New Test Cases 1. **Backend Error Message Mapping**: Map Chinese error to i18n key - Backend: "stdio 类型的 MCP 服务器必须包含 command 字段" - Frontend: mcp.error.commandRequired (6s toast duration) 2. **Cross-app Sync Logic**: Verify conditional sync behavior - claude → claude: setEnabled called, syncEnabledToClaude NOT called - Validates sync only occurs when crossing app types ## Minor Changes - McpPanel.test.tsx: Add trailing newline (formatter compliance) ## Test Coverage - Test files: 17 (unchanged) - Total tests: 112 → 119 (+7, +6.3%) - Execution time: 3.20s - All 119 tests passing ✅
2025-10-26 15:03:05 +08:00
{...rest}
/>,
);
return { onSave, onClose };
};
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
it("应用预设后填充 ID 与配置内容", async () => {
renderForm();
await waitFor(() =>
expect(screen.getByPlaceholderText("mcp.form.titlePlaceholder")).toBeInTheDocument(),
);
fireEvent.click(screen.getByText("preset-stdio"));
const idInput = screen.getByPlaceholderText(
"mcp.form.titlePlaceholder",
) as HTMLInputElement;
expect(idInput.value).toBe("preset-stdio");
const configTextarea = screen.getByPlaceholderText(
"mcp.form.jsonPlaceholder",
) as HTMLTextAreaElement;
expect(configTextarea.value).toBe('{\n "type": "stdio",\n "command": "preset-cmd"\n}');
});
it("提交时清洗字段并调用 upsert 与 onSave", async () => {
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
const { onSave } = renderForm();
fireEvent.change(screen.getByPlaceholderText("mcp.form.titlePlaceholder"), {
target: { value: " my-server " },
});
fireEvent.change(screen.getByPlaceholderText("mcp.form.namePlaceholder"), {
target: { value: " Friendly " },
});
fireEvent.click(screen.getByText("mcp.form.additionalInfo"));
fireEvent.change(screen.getByPlaceholderText("mcp.form.descriptionPlaceholder"), {
target: { value: " Description " },
});
fireEvent.change(screen.getByPlaceholderText("mcp.form.tagsPlaceholder"), {
target: { value: " tag1 , tag2 " },
});
fireEvent.change(screen.getByPlaceholderText("mcp.form.homepagePlaceholder"), {
target: { value: " https://example.com " },
});
fireEvent.change(screen.getByPlaceholderText("mcp.form.docsPlaceholder"), {
target: { value: " https://docs.example.com " },
});
fireEvent.change(screen.getByPlaceholderText("mcp.form.jsonPlaceholder"), {
target: { value: '{"type":"stdio","command":"run"}' },
});
fireEvent.click(screen.getByText("common.add"));
await waitFor(() => expect(upsertMock).toHaveBeenCalledTimes(1));
const [entry] = upsertMock.mock.calls.at(-1) ?? [];
expect(entry).toMatchObject({
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
id: "my-server",
name: "Friendly",
description: "Description",
homepage: "https://example.com",
docs: "https://docs.example.com",
tags: ["tag1", "tag2"],
server: {
type: "stdio",
command: "run",
},
apps: {
claude: true,
codex: true,
gemini: true,
},
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
});
expect(onSave).toHaveBeenCalledTimes(1);
expect(onSave).toHaveBeenCalledWith();
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
expect(toastErrorMock).not.toHaveBeenCalled();
});
it("缺少配置命令时阻止提交并提示错误", async () => {
renderForm();
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
fireEvent.change(screen.getByPlaceholderText("mcp.form.titlePlaceholder"), {
target: { value: "no-command" },
});
fireEvent.change(screen.getByPlaceholderText("mcp.form.jsonPlaceholder"), {
target: { value: '{"type":"stdio"}' },
});
fireEvent.click(screen.getByText("common.add"));
await waitFor(() => expect(toastErrorMock).toHaveBeenCalled());
expect(upsertMock).not.toHaveBeenCalled();
test: add comprehensive MCP UI test coverage with MSW infrastructure ## MSW Infrastructure Enhancement - Add 5 MCP API handlers to tests/msw/handlers.ts: - get_mcp_config: Fetch MCP configuration for app type - import_mcp_from_claude/codex: Mock import operations (returns count: 1) - set_mcp_enabled: Toggle MCP server enabled state - upsert_mcp_server_in_config: Create/update MCP server - delete_mcp_server_in_config: Remove MCP server - Add MCP state management to tests/msw/state.ts: - McpConfigState type with per-app server storage - Default test data (stdio server for Claude, http server for Codex) - CRUD functions: getMcpConfig, setMcpServerEnabled, upsertMcpServer, deleteMcpServer - Immutable state operations with deep cloning ## McpFormModal Component Tests (4 tests) - Test preset application: Verify ID and config JSON auto-fill from preset selection - Test conflict detection: Async validation shows warning when syncing to conflicting ID - Test field sanitization: Verify trim whitespace, split tags, clean URLs before save - Test validation errors: Block submit and show toast error for invalid stdio config (missing command) ## McpPanel Integration Tests (3 tests) - Test toggle enabled state: Click toggle button triggers useMcpActions.toggleEnabled with correct params - Test create server flow: Open form → submit → saveServer called with syncOtherSide option - Test delete server flow: Click delete → confirm dialog → deleteServer called with ID ## Test Utilities - Add createTestQueryClient helper with retry: false for faster test execution ## Test Coverage - Test files: 15 → 17 (+2) - Total tests: 105 → 112 (+6.7%) - All 112 tests passing - Execution time: 3.15s
2025-10-26 13:52:42 +08:00
const [message] = toastErrorMock.mock.calls.at(-1) ?? [];
expect(message).toBe("mcp.error.jsonInvalid");
});
test: extend MCP UI test coverage with wizard, TOML, and error handling ## McpFormModal Component Tests (+5 tests) ### Infrastructure Improvements - Enhance McpWizardModal mock from null to functional mock with testable onApply callback - Refactor renderForm helper to support custom onSave/onClose mock injection - Add McpServer type import for type-safe test data ### New Test Cases 1. **Wizard Integration**: Verify wizard generates config and auto-fills ID + JSON fields - Click "Use Wizard" → Apply → Form fields populated with wizard-id and config - Uses act() wrapper for React 18 async state updates 2. **TOML Auto-extraction (Codex)**: Test TOML → JSON conversion with ID extraction - Parse `[mcp.servers.demo]` → auto-fill ID as "demo" - Verify server object correctly parsed from TOML format - Codex-specific feature for config.toml compatibility 3. **TOML Validation Error**: Test missing required field handling - TOML with type="stdio" but no command → block submit - Display localized error toast: mcp.error.idRequired (3s duration) 4. **Edit Mode Immutability**: Verify ID field disabled during edit - ID input has disabled attribute and keeps original value - Config updates applied while enabled state preserved - syncOtherSide defaults to false in edit mode 5. **Error Recovery**: Test save failure button state restoration - Inject failing onSave mock → trigger error - Verify toast error displays translated message - Submit button disabled state resets to false for retry ## useMcpActions Hook Tests (+2 tests) ### New API Mocks - Add syncEnabledToClaude and syncEnabledToCodex mock functions ### New Test Cases 1. **Backend Error Message Mapping**: Map Chinese error to i18n key - Backend: "stdio 类型的 MCP 服务器必须包含 command 字段" - Frontend: mcp.error.commandRequired (6s toast duration) 2. **Cross-app Sync Logic**: Verify conditional sync behavior - claude → claude: setEnabled called, syncEnabledToClaude NOT called - Validates sync only occurs when crossing app types ## Minor Changes - McpPanel.test.tsx: Add trailing newline (formatter compliance) ## Test Coverage - Test files: 17 (unchanged) - Total tests: 112 → 119 (+7, +6.3%) - Execution time: 3.20s - All 119 tests passing ✅
2025-10-26 15:03:05 +08:00
it("支持向导生成配置并自动填充 ID", async () => {
renderForm();
fireEvent.click(screen.getByText("mcp.form.useWizard"));
const applyButton = await screen.findByTestId("wizard-apply");
await act(async () => {
fireEvent.click(applyButton);
});
const idInput = screen.getByPlaceholderText(
"mcp.form.titlePlaceholder",
) as HTMLInputElement;
expect(idInput.value).toBe("wizard-id");
const configTextarea = screen.getByPlaceholderText(
"mcp.form.jsonPlaceholder",
) as HTMLTextAreaElement;
expect(configTextarea.value).toBe('{"type":"stdio","command":"wizard-cmd"}');
});
it("TOML 模式下自动提取 ID 并成功保存", async () => {
const { onSave } = renderForm({ defaultFormat: "toml" });
test: extend MCP UI test coverage with wizard, TOML, and error handling ## McpFormModal Component Tests (+5 tests) ### Infrastructure Improvements - Enhance McpWizardModal mock from null to functional mock with testable onApply callback - Refactor renderForm helper to support custom onSave/onClose mock injection - Add McpServer type import for type-safe test data ### New Test Cases 1. **Wizard Integration**: Verify wizard generates config and auto-fills ID + JSON fields - Click "Use Wizard" → Apply → Form fields populated with wizard-id and config - Uses act() wrapper for React 18 async state updates 2. **TOML Auto-extraction (Codex)**: Test TOML → JSON conversion with ID extraction - Parse `[mcp.servers.demo]` → auto-fill ID as "demo" - Verify server object correctly parsed from TOML format - Codex-specific feature for config.toml compatibility 3. **TOML Validation Error**: Test missing required field handling - TOML with type="stdio" but no command → block submit - Display localized error toast: mcp.error.idRequired (3s duration) 4. **Edit Mode Immutability**: Verify ID field disabled during edit - ID input has disabled attribute and keeps original value - Config updates applied while enabled state preserved - syncOtherSide defaults to false in edit mode 5. **Error Recovery**: Test save failure button state restoration - Inject failing onSave mock → trigger error - Verify toast error displays translated message - Submit button disabled state resets to false for retry ## useMcpActions Hook Tests (+2 tests) ### New API Mocks - Add syncEnabledToClaude and syncEnabledToCodex mock functions ### New Test Cases 1. **Backend Error Message Mapping**: Map Chinese error to i18n key - Backend: "stdio 类型的 MCP 服务器必须包含 command 字段" - Frontend: mcp.error.commandRequired (6s toast duration) 2. **Cross-app Sync Logic**: Verify conditional sync behavior - claude → claude: setEnabled called, syncEnabledToClaude NOT called - Validates sync only occurs when crossing app types ## Minor Changes - McpPanel.test.tsx: Add trailing newline (formatter compliance) ## Test Coverage - Test files: 17 (unchanged) - Total tests: 112 → 119 (+7, +6.3%) - Execution time: 3.20s - All 119 tests passing ✅
2025-10-26 15:03:05 +08:00
const configTextarea = screen.getByPlaceholderText(
"mcp.form.tomlPlaceholder",
) as HTMLTextAreaElement;
const toml = `[mcp.servers.demo]
type = "stdio"
command = "run"
`;
fireEvent.change(configTextarea, { target: { value: toml } });
const idInput = screen.getByPlaceholderText(
"mcp.form.titlePlaceholder",
) as HTMLInputElement;
await waitFor(() => expect(idInput.value).toBe("demo"));
fireEvent.click(screen.getByText("common.add"));
await waitFor(() => expect(upsertMock).toHaveBeenCalledTimes(1));
const [entry] = upsertMock.mock.calls.at(-1) ?? [];
expect(entry.id).toBe("demo");
expect(entry.server).toEqual({ type: "stdio", command: "run" });
expect(onSave).toHaveBeenCalledTimes(1);
expect(onSave).toHaveBeenCalledWith();
test: extend MCP UI test coverage with wizard, TOML, and error handling ## McpFormModal Component Tests (+5 tests) ### Infrastructure Improvements - Enhance McpWizardModal mock from null to functional mock with testable onApply callback - Refactor renderForm helper to support custom onSave/onClose mock injection - Add McpServer type import for type-safe test data ### New Test Cases 1. **Wizard Integration**: Verify wizard generates config and auto-fills ID + JSON fields - Click "Use Wizard" → Apply → Form fields populated with wizard-id and config - Uses act() wrapper for React 18 async state updates 2. **TOML Auto-extraction (Codex)**: Test TOML → JSON conversion with ID extraction - Parse `[mcp.servers.demo]` → auto-fill ID as "demo" - Verify server object correctly parsed from TOML format - Codex-specific feature for config.toml compatibility 3. **TOML Validation Error**: Test missing required field handling - TOML with type="stdio" but no command → block submit - Display localized error toast: mcp.error.idRequired (3s duration) 4. **Edit Mode Immutability**: Verify ID field disabled during edit - ID input has disabled attribute and keeps original value - Config updates applied while enabled state preserved - syncOtherSide defaults to false in edit mode 5. **Error Recovery**: Test save failure button state restoration - Inject failing onSave mock → trigger error - Verify toast error displays translated message - Submit button disabled state resets to false for retry ## useMcpActions Hook Tests (+2 tests) ### New API Mocks - Add syncEnabledToClaude and syncEnabledToCodex mock functions ### New Test Cases 1. **Backend Error Message Mapping**: Map Chinese error to i18n key - Backend: "stdio 类型的 MCP 服务器必须包含 command 字段" - Frontend: mcp.error.commandRequired (6s toast duration) 2. **Cross-app Sync Logic**: Verify conditional sync behavior - claude → claude: setEnabled called, syncEnabledToClaude NOT called - Validates sync only occurs when crossing app types ## Minor Changes - McpPanel.test.tsx: Add trailing newline (formatter compliance) ## Test Coverage - Test files: 17 (unchanged) - Total tests: 112 → 119 (+7, +6.3%) - Execution time: 3.20s - All 119 tests passing ✅
2025-10-26 15:03:05 +08:00
expect(toastErrorMock).not.toHaveBeenCalled();
});
it("TOML 模式下缺少命令时展示错误提示并阻止提交", async () => {
renderForm({ defaultFormat: "toml" });
test: extend MCP UI test coverage with wizard, TOML, and error handling ## McpFormModal Component Tests (+5 tests) ### Infrastructure Improvements - Enhance McpWizardModal mock from null to functional mock with testable onApply callback - Refactor renderForm helper to support custom onSave/onClose mock injection - Add McpServer type import for type-safe test data ### New Test Cases 1. **Wizard Integration**: Verify wizard generates config and auto-fills ID + JSON fields - Click "Use Wizard" → Apply → Form fields populated with wizard-id and config - Uses act() wrapper for React 18 async state updates 2. **TOML Auto-extraction (Codex)**: Test TOML → JSON conversion with ID extraction - Parse `[mcp.servers.demo]` → auto-fill ID as "demo" - Verify server object correctly parsed from TOML format - Codex-specific feature for config.toml compatibility 3. **TOML Validation Error**: Test missing required field handling - TOML with type="stdio" but no command → block submit - Display localized error toast: mcp.error.idRequired (3s duration) 4. **Edit Mode Immutability**: Verify ID field disabled during edit - ID input has disabled attribute and keeps original value - Config updates applied while enabled state preserved - syncOtherSide defaults to false in edit mode 5. **Error Recovery**: Test save failure button state restoration - Inject failing onSave mock → trigger error - Verify toast error displays translated message - Submit button disabled state resets to false for retry ## useMcpActions Hook Tests (+2 tests) ### New API Mocks - Add syncEnabledToClaude and syncEnabledToCodex mock functions ### New Test Cases 1. **Backend Error Message Mapping**: Map Chinese error to i18n key - Backend: "stdio 类型的 MCP 服务器必须包含 command 字段" - Frontend: mcp.error.commandRequired (6s toast duration) 2. **Cross-app Sync Logic**: Verify conditional sync behavior - claude → claude: setEnabled called, syncEnabledToClaude NOT called - Validates sync only occurs when crossing app types ## Minor Changes - McpPanel.test.tsx: Add trailing newline (formatter compliance) ## Test Coverage - Test files: 17 (unchanged) - Total tests: 112 → 119 (+7, +6.3%) - Execution time: 3.20s - All 119 tests passing ✅
2025-10-26 15:03:05 +08:00
// 填写 ID 字段
fireEvent.change(screen.getByPlaceholderText("mcp.form.titlePlaceholder"), {
target: { value: "test-toml" },
});
test: extend MCP UI test coverage with wizard, TOML, and error handling ## McpFormModal Component Tests (+5 tests) ### Infrastructure Improvements - Enhance McpWizardModal mock from null to functional mock with testable onApply callback - Refactor renderForm helper to support custom onSave/onClose mock injection - Add McpServer type import for type-safe test data ### New Test Cases 1. **Wizard Integration**: Verify wizard generates config and auto-fills ID + JSON fields - Click "Use Wizard" → Apply → Form fields populated with wizard-id and config - Uses act() wrapper for React 18 async state updates 2. **TOML Auto-extraction (Codex)**: Test TOML → JSON conversion with ID extraction - Parse `[mcp.servers.demo]` → auto-fill ID as "demo" - Verify server object correctly parsed from TOML format - Codex-specific feature for config.toml compatibility 3. **TOML Validation Error**: Test missing required field handling - TOML with type="stdio" but no command → block submit - Display localized error toast: mcp.error.idRequired (3s duration) 4. **Edit Mode Immutability**: Verify ID field disabled during edit - ID input has disabled attribute and keeps original value - Config updates applied while enabled state preserved - syncOtherSide defaults to false in edit mode 5. **Error Recovery**: Test save failure button state restoration - Inject failing onSave mock → trigger error - Verify toast error displays translated message - Submit button disabled state resets to false for retry ## useMcpActions Hook Tests (+2 tests) ### New API Mocks - Add syncEnabledToClaude and syncEnabledToCodex mock functions ### New Test Cases 1. **Backend Error Message Mapping**: Map Chinese error to i18n key - Backend: "stdio 类型的 MCP 服务器必须包含 command 字段" - Frontend: mcp.error.commandRequired (6s toast duration) 2. **Cross-app Sync Logic**: Verify conditional sync behavior - claude → claude: setEnabled called, syncEnabledToClaude NOT called - Validates sync only occurs when crossing app types ## Minor Changes - McpPanel.test.tsx: Add trailing newline (formatter compliance) ## Test Coverage - Test files: 17 (unchanged) - Total tests: 112 → 119 (+7, +6.3%) - Execution time: 3.20s - All 119 tests passing ✅
2025-10-26 15:03:05 +08:00
const configTextarea = screen.getByPlaceholderText(
"mcp.form.tomlPlaceholder",
) as HTMLTextAreaElement;
const invalidToml = `[mcp.servers.demo]
type = "stdio"
`;
fireEvent.change(configTextarea, { target: { value: invalidToml } });
fireEvent.click(screen.getByText("common.add"));
await waitFor(() =>
expect(toastErrorMock).toHaveBeenCalledWith("mcp.error.tomlInvalid", {
test: extend MCP UI test coverage with wizard, TOML, and error handling ## McpFormModal Component Tests (+5 tests) ### Infrastructure Improvements - Enhance McpWizardModal mock from null to functional mock with testable onApply callback - Refactor renderForm helper to support custom onSave/onClose mock injection - Add McpServer type import for type-safe test data ### New Test Cases 1. **Wizard Integration**: Verify wizard generates config and auto-fills ID + JSON fields - Click "Use Wizard" → Apply → Form fields populated with wizard-id and config - Uses act() wrapper for React 18 async state updates 2. **TOML Auto-extraction (Codex)**: Test TOML → JSON conversion with ID extraction - Parse `[mcp.servers.demo]` → auto-fill ID as "demo" - Verify server object correctly parsed from TOML format - Codex-specific feature for config.toml compatibility 3. **TOML Validation Error**: Test missing required field handling - TOML with type="stdio" but no command → block submit - Display localized error toast: mcp.error.idRequired (3s duration) 4. **Edit Mode Immutability**: Verify ID field disabled during edit - ID input has disabled attribute and keeps original value - Config updates applied while enabled state preserved - syncOtherSide defaults to false in edit mode 5. **Error Recovery**: Test save failure button state restoration - Inject failing onSave mock → trigger error - Verify toast error displays translated message - Submit button disabled state resets to false for retry ## useMcpActions Hook Tests (+2 tests) ### New API Mocks - Add syncEnabledToClaude and syncEnabledToCodex mock functions ### New Test Cases 1. **Backend Error Message Mapping**: Map Chinese error to i18n key - Backend: "stdio 类型的 MCP 服务器必须包含 command 字段" - Frontend: mcp.error.commandRequired (6s toast duration) 2. **Cross-app Sync Logic**: Verify conditional sync behavior - claude → claude: setEnabled called, syncEnabledToClaude NOT called - Validates sync only occurs when crossing app types ## Minor Changes - McpPanel.test.tsx: Add trailing newline (formatter compliance) ## Test Coverage - Test files: 17 (unchanged) - Total tests: 112 → 119 (+7, +6.3%) - Execution time: 3.20s - All 119 tests passing ✅
2025-10-26 15:03:05 +08:00
duration: 3000,
}),
);
expect(upsertMock).not.toHaveBeenCalled();
test: extend MCP UI test coverage with wizard, TOML, and error handling ## McpFormModal Component Tests (+5 tests) ### Infrastructure Improvements - Enhance McpWizardModal mock from null to functional mock with testable onApply callback - Refactor renderForm helper to support custom onSave/onClose mock injection - Add McpServer type import for type-safe test data ### New Test Cases 1. **Wizard Integration**: Verify wizard generates config and auto-fills ID + JSON fields - Click "Use Wizard" → Apply → Form fields populated with wizard-id and config - Uses act() wrapper for React 18 async state updates 2. **TOML Auto-extraction (Codex)**: Test TOML → JSON conversion with ID extraction - Parse `[mcp.servers.demo]` → auto-fill ID as "demo" - Verify server object correctly parsed from TOML format - Codex-specific feature for config.toml compatibility 3. **TOML Validation Error**: Test missing required field handling - TOML with type="stdio" but no command → block submit - Display localized error toast: mcp.error.idRequired (3s duration) 4. **Edit Mode Immutability**: Verify ID field disabled during edit - ID input has disabled attribute and keeps original value - Config updates applied while enabled state preserved - syncOtherSide defaults to false in edit mode 5. **Error Recovery**: Test save failure button state restoration - Inject failing onSave mock → trigger error - Verify toast error displays translated message - Submit button disabled state resets to false for retry ## useMcpActions Hook Tests (+2 tests) ### New API Mocks - Add syncEnabledToClaude and syncEnabledToCodex mock functions ### New Test Cases 1. **Backend Error Message Mapping**: Map Chinese error to i18n key - Backend: "stdio 类型的 MCP 服务器必须包含 command 字段" - Frontend: mcp.error.commandRequired (6s toast duration) 2. **Cross-app Sync Logic**: Verify conditional sync behavior - claude → claude: setEnabled called, syncEnabledToClaude NOT called - Validates sync only occurs when crossing app types ## Minor Changes - McpPanel.test.tsx: Add trailing newline (formatter compliance) ## Test Coverage - Test files: 17 (unchanged) - Total tests: 112 → 119 (+7, +6.3%) - Execution time: 3.20s - All 119 tests passing ✅
2025-10-26 15:03:05 +08:00
});
it("编辑模式下保持 ID 并更新配置", async () => {
const initialData: McpServer = {
id: "existing",
name: "Existing",
enabled: true,
description: "Old desc",
server: { type: "stdio", command: "old" },
apps: { claude: true, codex: false, gemini: false },
test: extend MCP UI test coverage with wizard, TOML, and error handling ## McpFormModal Component Tests (+5 tests) ### Infrastructure Improvements - Enhance McpWizardModal mock from null to functional mock with testable onApply callback - Refactor renderForm helper to support custom onSave/onClose mock injection - Add McpServer type import for type-safe test data ### New Test Cases 1. **Wizard Integration**: Verify wizard generates config and auto-fills ID + JSON fields - Click "Use Wizard" → Apply → Form fields populated with wizard-id and config - Uses act() wrapper for React 18 async state updates 2. **TOML Auto-extraction (Codex)**: Test TOML → JSON conversion with ID extraction - Parse `[mcp.servers.demo]` → auto-fill ID as "demo" - Verify server object correctly parsed from TOML format - Codex-specific feature for config.toml compatibility 3. **TOML Validation Error**: Test missing required field handling - TOML with type="stdio" but no command → block submit - Display localized error toast: mcp.error.idRequired (3s duration) 4. **Edit Mode Immutability**: Verify ID field disabled during edit - ID input has disabled attribute and keeps original value - Config updates applied while enabled state preserved - syncOtherSide defaults to false in edit mode 5. **Error Recovery**: Test save failure button state restoration - Inject failing onSave mock → trigger error - Verify toast error displays translated message - Submit button disabled state resets to false for retry ## useMcpActions Hook Tests (+2 tests) ### New API Mocks - Add syncEnabledToClaude and syncEnabledToCodex mock functions ### New Test Cases 1. **Backend Error Message Mapping**: Map Chinese error to i18n key - Backend: "stdio 类型的 MCP 服务器必须包含 command 字段" - Frontend: mcp.error.commandRequired (6s toast duration) 2. **Cross-app Sync Logic**: Verify conditional sync behavior - claude → claude: setEnabled called, syncEnabledToClaude NOT called - Validates sync only occurs when crossing app types ## Minor Changes - McpPanel.test.tsx: Add trailing newline (formatter compliance) ## Test Coverage - Test files: 17 (unchanged) - Total tests: 112 → 119 (+7, +6.3%) - Execution time: 3.20s - All 119 tests passing ✅
2025-10-26 15:03:05 +08:00
} as McpServer;
const { onSave } = renderForm({
editingId: "existing",
initialData,
});
const idInput = screen.getByPlaceholderText(
"mcp.form.titlePlaceholder",
) as HTMLInputElement;
expect(idInput.value).toBe("existing");
expect(idInput).toHaveAttribute("disabled");
const configTextarea = screen.getByPlaceholderText(
"mcp.form.jsonPlaceholder",
) as HTMLTextAreaElement;
expect(configTextarea.value).toContain("\"command\": \"old\"");
fireEvent.change(configTextarea, {
target: { value: '{"type":"stdio","command":"updated"}' },
});
fireEvent.click(screen.getByText("common.save"));
await waitFor(() => expect(upsertMock).toHaveBeenCalledTimes(1));
const [entry] = upsertMock.mock.calls.at(-1) ?? [];
expect(entry.id).toBe("existing");
test: extend MCP UI test coverage with wizard, TOML, and error handling ## McpFormModal Component Tests (+5 tests) ### Infrastructure Improvements - Enhance McpWizardModal mock from null to functional mock with testable onApply callback - Refactor renderForm helper to support custom onSave/onClose mock injection - Add McpServer type import for type-safe test data ### New Test Cases 1. **Wizard Integration**: Verify wizard generates config and auto-fills ID + JSON fields - Click "Use Wizard" → Apply → Form fields populated with wizard-id and config - Uses act() wrapper for React 18 async state updates 2. **TOML Auto-extraction (Codex)**: Test TOML → JSON conversion with ID extraction - Parse `[mcp.servers.demo]` → auto-fill ID as "demo" - Verify server object correctly parsed from TOML format - Codex-specific feature for config.toml compatibility 3. **TOML Validation Error**: Test missing required field handling - TOML with type="stdio" but no command → block submit - Display localized error toast: mcp.error.idRequired (3s duration) 4. **Edit Mode Immutability**: Verify ID field disabled during edit - ID input has disabled attribute and keeps original value - Config updates applied while enabled state preserved - syncOtherSide defaults to false in edit mode 5. **Error Recovery**: Test save failure button state restoration - Inject failing onSave mock → trigger error - Verify toast error displays translated message - Submit button disabled state resets to false for retry ## useMcpActions Hook Tests (+2 tests) ### New API Mocks - Add syncEnabledToClaude and syncEnabledToCodex mock functions ### New Test Cases 1. **Backend Error Message Mapping**: Map Chinese error to i18n key - Backend: "stdio 类型的 MCP 服务器必须包含 command 字段" - Frontend: mcp.error.commandRequired (6s toast duration) 2. **Cross-app Sync Logic**: Verify conditional sync behavior - claude → claude: setEnabled called, syncEnabledToClaude NOT called - Validates sync only occurs when crossing app types ## Minor Changes - McpPanel.test.tsx: Add trailing newline (formatter compliance) ## Test Coverage - Test files: 17 (unchanged) - Total tests: 112 → 119 (+7, +6.3%) - Execution time: 3.20s - All 119 tests passing ✅
2025-10-26 15:03:05 +08:00
expect(entry.server.command).toBe("updated");
expect(entry.enabled).toBe(true);
expect(entry.apps).toEqual({
claude: true,
codex: false,
gemini: false,
});
expect(onSave).toHaveBeenCalledTimes(1);
expect(onSave).toHaveBeenCalledWith();
});
it("允许未选择任何应用保存配置,并保持 apps 全 false", async () => {
const { onSave } = renderForm();
fireEvent.change(screen.getByPlaceholderText("mcp.form.titlePlaceholder"), {
target: { value: "no-apps" },
});
fireEvent.change(screen.getByPlaceholderText("mcp.form.jsonPlaceholder"), {
target: { value: '{"type":"stdio","command":"run"}' },
});
const claudeCheckbox = screen.getByLabelText(
"mcp.unifiedPanel.apps.claude",
) as HTMLInputElement;
expect(claudeCheckbox.checked).toBe(true);
fireEvent.click(claudeCheckbox);
const codexCheckbox = screen.getByLabelText(
"mcp.unifiedPanel.apps.codex",
) as HTMLInputElement;
expect(codexCheckbox.checked).toBe(true);
fireEvent.click(codexCheckbox);
const geminiCheckbox = screen.getByLabelText(
"mcp.unifiedPanel.apps.gemini",
) as HTMLInputElement;
expect(geminiCheckbox.checked).toBe(true);
fireEvent.click(geminiCheckbox);
fireEvent.click(screen.getByText("common.add"));
await waitFor(() => expect(upsertMock).toHaveBeenCalledTimes(1));
const [entry] = upsertMock.mock.calls.at(-1) ?? [];
expect(entry.id).toBe("no-apps");
expect(entry.apps).toEqual({
claude: false,
codex: false,
gemini: false,
});
expect(onSave).toHaveBeenCalledTimes(1);
expect(toastErrorMock).not.toHaveBeenCalled();
test: extend MCP UI test coverage with wizard, TOML, and error handling ## McpFormModal Component Tests (+5 tests) ### Infrastructure Improvements - Enhance McpWizardModal mock from null to functional mock with testable onApply callback - Refactor renderForm helper to support custom onSave/onClose mock injection - Add McpServer type import for type-safe test data ### New Test Cases 1. **Wizard Integration**: Verify wizard generates config and auto-fills ID + JSON fields - Click "Use Wizard" → Apply → Form fields populated with wizard-id and config - Uses act() wrapper for React 18 async state updates 2. **TOML Auto-extraction (Codex)**: Test TOML → JSON conversion with ID extraction - Parse `[mcp.servers.demo]` → auto-fill ID as "demo" - Verify server object correctly parsed from TOML format - Codex-specific feature for config.toml compatibility 3. **TOML Validation Error**: Test missing required field handling - TOML with type="stdio" but no command → block submit - Display localized error toast: mcp.error.idRequired (3s duration) 4. **Edit Mode Immutability**: Verify ID field disabled during edit - ID input has disabled attribute and keeps original value - Config updates applied while enabled state preserved - syncOtherSide defaults to false in edit mode 5. **Error Recovery**: Test save failure button state restoration - Inject failing onSave mock → trigger error - Verify toast error displays translated message - Submit button disabled state resets to false for retry ## useMcpActions Hook Tests (+2 tests) ### New API Mocks - Add syncEnabledToClaude and syncEnabledToCodex mock functions ### New Test Cases 1. **Backend Error Message Mapping**: Map Chinese error to i18n key - Backend: "stdio 类型的 MCP 服务器必须包含 command 字段" - Frontend: mcp.error.commandRequired (6s toast duration) 2. **Cross-app Sync Logic**: Verify conditional sync behavior - claude → claude: setEnabled called, syncEnabledToClaude NOT called - Validates sync only occurs when crossing app types ## Minor Changes - McpPanel.test.tsx: Add trailing newline (formatter compliance) ## Test Coverage - Test files: 17 (unchanged) - Total tests: 112 → 119 (+7, +6.3%) - Execution time: 3.20s - All 119 tests passing ✅
2025-10-26 15:03:05 +08:00
});
it("保存失败时展示翻译后的错误并恢复按钮", async () => {
const failingSave = vi.fn().mockRejectedValue(new Error("保存失败"));
renderForm({ onSave: failingSave });
fireEvent.change(screen.getByPlaceholderText("mcp.form.titlePlaceholder"), {
target: { value: "will-fail" },
});
fireEvent.change(screen.getByPlaceholderText("mcp.form.jsonPlaceholder"), {
target: { value: '{"type":"stdio","command":"ok"}' },
});
fireEvent.click(screen.getByText("common.add"));
await waitFor(() => expect(failingSave).toHaveBeenCalled());
await waitFor(() => expect(toastErrorMock).toHaveBeenCalled());
const [message] = toastErrorMock.mock.calls.at(-1) ?? [];
expect(message).toBe("保存失败");
const addButton = screen.getByText("common.add") as HTMLButtonElement;
expect(addButton.disabled).toBe(false);
});
});