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

451 lines
13 KiB
TypeScript
Raw 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: update test suites to match component refactoring Comprehensive test updates to align with recent component refactoring and new auto-launch functionality. Component Tests: - AddProviderDialog.test.tsx (10 lines): * Updated test cases for new dialog behavior * Enhanced mock data for preset selection * Improved assertions for validation - ImportExportSection.test.tsx (16 lines): * Updated for new settings page integration * Enhanced test coverage for error scenarios * Better mock state management - McpFormModal.test.tsx (60 lines): * Extensive updates for form refactoring * New test cases for multi-app selection * Enhanced validation testing * Better coverage of stdio/http server types - ProviderList.test.tsx (11 lines): * Updated for new card layout * Enhanced drag-and-drop testing - SettingsDialog.test.tsx (96 lines): * Major updates for SettingsPage migration * New test cases for auto-launch functionality * Enhanced integration test coverage * Better async operation testing Hook Tests: - useDirectorySettings.test.tsx (32 lines): * Updated for refactored hook logic * Enhanced test coverage for edge cases - useDragSort.test.tsx (36 lines): * Simplified test cases * Better mock implementation * Improved assertions - useImportExport tests (16 lines total): * Updated for new error handling * Enhanced test coverage - useMcpValidation.test.tsx (23 lines): * Updated validation test cases * Better coverage of error scenarios - useProviderActions.test.tsx (48 lines): * Extensive updates for hook refactoring * New test cases for provider operations * Enhanced mock data - useSettings.test.tsx (12 lines): * New test cases for auto-launch * Enhanced settings state testing * Better async operation coverage Integration Tests: - App.test.tsx (41 lines): * Updated for new routing logic * Enhanced navigation testing * Better component integration coverage - SettingsDialog.test.tsx (88 lines): * Complete rewrite for SettingsPage * New integration test scenarios * Enhanced user workflow testing Mock Infrastructure: - handlers.ts (117 lines): * Major updates for MSW handlers * New handlers for auto-launch commands * Enhanced error simulation * Better request/response mocking - state.ts (37 lines): * Updated mock state structure * New state for auto-launch * Enhanced state reset functionality - tauriMocks.ts (10 lines): * Updated mock implementations * Better type safety - server.ts & testQueryClient.ts: * Minor cleanup (2 lines removed) Test Infrastructure Improvements: - Better test isolation - Enhanced mock data consistency - Improved async operation testing - Better error scenario coverage - Enhanced integration test patterns Coverage Improvements: - Net increase of 195 lines of test code - Better coverage of edge cases - Enhanced error path testing - Improved integration test scenarios - Better mock infrastructure All tests now pass with the refactored components while maintaining comprehensive coverage of functionality and edge cases.
2025-11-21 11:12:06 +08:00
import {
render,
screen,
fireEvent,
waitFor,
act,
} from "@testing-library/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 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}
test: update test suites to match component refactoring Comprehensive test updates to align with recent component refactoring and new auto-launch functionality. Component Tests: - AddProviderDialog.test.tsx (10 lines): * Updated test cases for new dialog behavior * Enhanced mock data for preset selection * Improved assertions for validation - ImportExportSection.test.tsx (16 lines): * Updated for new settings page integration * Enhanced test coverage for error scenarios * Better mock state management - McpFormModal.test.tsx (60 lines): * Extensive updates for form refactoring * New test cases for multi-app selection * Enhanced validation testing * Better coverage of stdio/http server types - ProviderList.test.tsx (11 lines): * Updated for new card layout * Enhanced drag-and-drop testing - SettingsDialog.test.tsx (96 lines): * Major updates for SettingsPage migration * New test cases for auto-launch functionality * Enhanced integration test coverage * Better async operation testing Hook Tests: - useDirectorySettings.test.tsx (32 lines): * Updated for refactored hook logic * Enhanced test coverage for edge cases - useDragSort.test.tsx (36 lines): * Simplified test cases * Better mock implementation * Improved assertions - useImportExport tests (16 lines total): * Updated for new error handling * Enhanced test coverage - useMcpValidation.test.tsx (23 lines): * Updated validation test cases * Better coverage of error scenarios - useProviderActions.test.tsx (48 lines): * Extensive updates for hook refactoring * New test cases for provider operations * Enhanced mock data - useSettings.test.tsx (12 lines): * New test cases for auto-launch * Enhanced settings state testing * Better async operation coverage Integration Tests: - App.test.tsx (41 lines): * Updated for new routing logic * Enhanced navigation testing * Better component integration coverage - SettingsDialog.test.tsx (88 lines): * Complete rewrite for SettingsPage * New integration test scenarios * Enhanced user workflow testing Mock Infrastructure: - handlers.ts (117 lines): * Major updates for MSW handlers * New handlers for auto-launch commands * Enhanced error simulation * Better request/response mocking - state.ts (37 lines): * Updated mock state structure * New state for auto-launch * Enhanced state reset functionality - tauriMocks.ts (10 lines): * Updated mock implementations * Better type safety - server.ts & testQueryClient.ts: * Minor cleanup (2 lines removed) Test Infrastructure Improvements: - Better test isolation - Enhanced mock data consistency - Improved async operation testing - Better error scenario coverage - Enhanced integration test patterns Coverage Improvements: - Net increase of 195 lines of test code - Better coverage of edge cases - Enhanced error path testing - Improved integration test scenarios - Better mock infrastructure All tests now pass with the refactored components while maintaining comprehensive coverage of functionality and edge cases.
2025-11-21 11:12:06 +08:00
onChange={(event) =>
onChange?.({ target: { value: event.target.value } })
}
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
{...rest}
/>
),
}));
vi.mock("@/components/ui/textarea", () => ({
Textarea: ({ value, onChange, ...rest }: any) => (
<textarea
value={value}
test: update test suites to match component refactoring Comprehensive test updates to align with recent component refactoring and new auto-launch functionality. Component Tests: - AddProviderDialog.test.tsx (10 lines): * Updated test cases for new dialog behavior * Enhanced mock data for preset selection * Improved assertions for validation - ImportExportSection.test.tsx (16 lines): * Updated for new settings page integration * Enhanced test coverage for error scenarios * Better mock state management - McpFormModal.test.tsx (60 lines): * Extensive updates for form refactoring * New test cases for multi-app selection * Enhanced validation testing * Better coverage of stdio/http server types - ProviderList.test.tsx (11 lines): * Updated for new card layout * Enhanced drag-and-drop testing - SettingsDialog.test.tsx (96 lines): * Major updates for SettingsPage migration * New test cases for auto-launch functionality * Enhanced integration test coverage * Better async operation testing Hook Tests: - useDirectorySettings.test.tsx (32 lines): * Updated for refactored hook logic * Enhanced test coverage for edge cases - useDragSort.test.tsx (36 lines): * Simplified test cases * Better mock implementation * Improved assertions - useImportExport tests (16 lines total): * Updated for new error handling * Enhanced test coverage - useMcpValidation.test.tsx (23 lines): * Updated validation test cases * Better coverage of error scenarios - useProviderActions.test.tsx (48 lines): * Extensive updates for hook refactoring * New test cases for provider operations * Enhanced mock data - useSettings.test.tsx (12 lines): * New test cases for auto-launch * Enhanced settings state testing * Better async operation coverage Integration Tests: - App.test.tsx (41 lines): * Updated for new routing logic * Enhanced navigation testing * Better component integration coverage - SettingsDialog.test.tsx (88 lines): * Complete rewrite for SettingsPage * New integration test scenarios * Enhanced user workflow testing Mock Infrastructure: - handlers.ts (117 lines): * Major updates for MSW handlers * New handlers for auto-launch commands * Enhanced error simulation * Better request/response mocking - state.ts (37 lines): * Updated mock state structure * New state for auto-launch * Enhanced state reset functionality - tauriMocks.ts (10 lines): * Updated mock implementations * Better type safety - server.ts & testQueryClient.ts: * Minor cleanup (2 lines removed) Test Infrastructure Improvements: - Better test isolation - Enhanced mock data consistency - Improved async operation testing - Better error scenario coverage - Enhanced integration test patterns Coverage Improvements: - Net increase of 195 lines of test code - Better coverage of edge cases - Enhanced error path testing - Improved integration test scenarios - Better mock infrastructure All tests now pass with the refactored components while maintaining comprehensive coverage of functionality and edge cases.
2025-11-21 11:12:06 +08:00
onChange={(event) =>
onChange?.({ target: { value: event.target.value } })
}
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
{...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 () => {
test: update test suites to match component refactoring Comprehensive test updates to align with recent component refactoring and new auto-launch functionality. Component Tests: - AddProviderDialog.test.tsx (10 lines): * Updated test cases for new dialog behavior * Enhanced mock data for preset selection * Improved assertions for validation - ImportExportSection.test.tsx (16 lines): * Updated for new settings page integration * Enhanced test coverage for error scenarios * Better mock state management - McpFormModal.test.tsx (60 lines): * Extensive updates for form refactoring * New test cases for multi-app selection * Enhanced validation testing * Better coverage of stdio/http server types - ProviderList.test.tsx (11 lines): * Updated for new card layout * Enhanced drag-and-drop testing - SettingsDialog.test.tsx (96 lines): * Major updates for SettingsPage migration * New test cases for auto-launch functionality * Enhanced integration test coverage * Better async operation testing Hook Tests: - useDirectorySettings.test.tsx (32 lines): * Updated for refactored hook logic * Enhanced test coverage for edge cases - useDragSort.test.tsx (36 lines): * Simplified test cases * Better mock implementation * Improved assertions - useImportExport tests (16 lines total): * Updated for new error handling * Enhanced test coverage - useMcpValidation.test.tsx (23 lines): * Updated validation test cases * Better coverage of error scenarios - useProviderActions.test.tsx (48 lines): * Extensive updates for hook refactoring * New test cases for provider operations * Enhanced mock data - useSettings.test.tsx (12 lines): * New test cases for auto-launch * Enhanced settings state testing * Better async operation coverage Integration Tests: - App.test.tsx (41 lines): * Updated for new routing logic * Enhanced navigation testing * Better component integration coverage - SettingsDialog.test.tsx (88 lines): * Complete rewrite for SettingsPage * New integration test scenarios * Enhanced user workflow testing Mock Infrastructure: - handlers.ts (117 lines): * Major updates for MSW handlers * New handlers for auto-launch commands * Enhanced error simulation * Better request/response mocking - state.ts (37 lines): * Updated mock state structure * New state for auto-launch * Enhanced state reset functionality - tauriMocks.ts (10 lines): * Updated mock implementations * Better type safety - server.ts & testQueryClient.ts: * Minor cleanup (2 lines removed) Test Infrastructure Improvements: - Better test isolation - Enhanced mock data consistency - Improved async operation testing - Better error scenario coverage - Enhanced integration test patterns Coverage Improvements: - Net increase of 195 lines of test code - Better coverage of edge cases - Enhanced error path testing - Improved integration test scenarios - Better mock infrastructure All tests now pass with the refactored components while maintaining comprehensive coverage of functionality and edge cases.
2025-11-21 11:12:06 +08:00
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>>,
) => {
test: update test suites to match component refactoring Comprehensive test updates to align with recent component refactoring and new auto-launch functionality. Component Tests: - AddProviderDialog.test.tsx (10 lines): * Updated test cases for new dialog behavior * Enhanced mock data for preset selection * Improved assertions for validation - ImportExportSection.test.tsx (16 lines): * Updated for new settings page integration * Enhanced test coverage for error scenarios * Better mock state management - McpFormModal.test.tsx (60 lines): * Extensive updates for form refactoring * New test cases for multi-app selection * Enhanced validation testing * Better coverage of stdio/http server types - ProviderList.test.tsx (11 lines): * Updated for new card layout * Enhanced drag-and-drop testing - SettingsDialog.test.tsx (96 lines): * Major updates for SettingsPage migration * New test cases for auto-launch functionality * Enhanced integration test coverage * Better async operation testing Hook Tests: - useDirectorySettings.test.tsx (32 lines): * Updated for refactored hook logic * Enhanced test coverage for edge cases - useDragSort.test.tsx (36 lines): * Simplified test cases * Better mock implementation * Improved assertions - useImportExport tests (16 lines total): * Updated for new error handling * Enhanced test coverage - useMcpValidation.test.tsx (23 lines): * Updated validation test cases * Better coverage of error scenarios - useProviderActions.test.tsx (48 lines): * Extensive updates for hook refactoring * New test cases for provider operations * Enhanced mock data - useSettings.test.tsx (12 lines): * New test cases for auto-launch * Enhanced settings state testing * Better async operation coverage Integration Tests: - App.test.tsx (41 lines): * Updated for new routing logic * Enhanced navigation testing * Better component integration coverage - SettingsDialog.test.tsx (88 lines): * Complete rewrite for SettingsPage * New integration test scenarios * Enhanced user workflow testing Mock Infrastructure: - handlers.ts (117 lines): * Major updates for MSW handlers * New handlers for auto-launch commands * Enhanced error simulation * Better request/response mocking - state.ts (37 lines): * Updated mock state structure * New state for auto-launch * Enhanced state reset functionality - tauriMocks.ts (10 lines): * Updated mock implementations * Better type safety - server.ts & testQueryClient.ts: * Minor cleanup (2 lines removed) Test Infrastructure Improvements: - Better test isolation - Enhanced mock data consistency - Improved async operation testing - Better error scenario coverage - Enhanced integration test patterns Coverage Improvements: - Net increase of 195 lines of test code - Better coverage of edge cases - Enhanced error path testing - Improved integration test scenarios - Better mock infrastructure All tests now pass with the refactored components while maintaining comprehensive coverage of functionality and edge cases.
2025-11-21 11:12:06 +08:00
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(() =>
test: update test suites to match component refactoring Comprehensive test updates to align with recent component refactoring and new auto-launch functionality. Component Tests: - AddProviderDialog.test.tsx (10 lines): * Updated test cases for new dialog behavior * Enhanced mock data for preset selection * Improved assertions for validation - ImportExportSection.test.tsx (16 lines): * Updated for new settings page integration * Enhanced test coverage for error scenarios * Better mock state management - McpFormModal.test.tsx (60 lines): * Extensive updates for form refactoring * New test cases for multi-app selection * Enhanced validation testing * Better coverage of stdio/http server types - ProviderList.test.tsx (11 lines): * Updated for new card layout * Enhanced drag-and-drop testing - SettingsDialog.test.tsx (96 lines): * Major updates for SettingsPage migration * New test cases for auto-launch functionality * Enhanced integration test coverage * Better async operation testing Hook Tests: - useDirectorySettings.test.tsx (32 lines): * Updated for refactored hook logic * Enhanced test coverage for edge cases - useDragSort.test.tsx (36 lines): * Simplified test cases * Better mock implementation * Improved assertions - useImportExport tests (16 lines total): * Updated for new error handling * Enhanced test coverage - useMcpValidation.test.tsx (23 lines): * Updated validation test cases * Better coverage of error scenarios - useProviderActions.test.tsx (48 lines): * Extensive updates for hook refactoring * New test cases for provider operations * Enhanced mock data - useSettings.test.tsx (12 lines): * New test cases for auto-launch * Enhanced settings state testing * Better async operation coverage Integration Tests: - App.test.tsx (41 lines): * Updated for new routing logic * Enhanced navigation testing * Better component integration coverage - SettingsDialog.test.tsx (88 lines): * Complete rewrite for SettingsPage * New integration test scenarios * Enhanced user workflow testing Mock Infrastructure: - handlers.ts (117 lines): * Major updates for MSW handlers * New handlers for auto-launch commands * Enhanced error simulation * Better request/response mocking - state.ts (37 lines): * Updated mock state structure * New state for auto-launch * Enhanced state reset functionality - tauriMocks.ts (10 lines): * Updated mock implementations * Better type safety - server.ts & testQueryClient.ts: * Minor cleanup (2 lines removed) Test Infrastructure Improvements: - Better test isolation - Enhanced mock data consistency - Improved async operation testing - Better error scenario coverage - Enhanced integration test patterns Coverage Improvements: - Net increase of 195 lines of test code - Better coverage of edge cases - Enhanced error path testing - Improved integration test scenarios - Better mock infrastructure All tests now pass with the refactored components while maintaining comprehensive coverage of functionality and edge cases.
2025-11-21 11:12:06 +08:00
expect(
screen.getByPlaceholderText("mcp.form.titlePlaceholder"),
).toBeInTheDocument(),
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.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;
test: update test suites to match component refactoring Comprehensive test updates to align with recent component refactoring and new auto-launch functionality. Component Tests: - AddProviderDialog.test.tsx (10 lines): * Updated test cases for new dialog behavior * Enhanced mock data for preset selection * Improved assertions for validation - ImportExportSection.test.tsx (16 lines): * Updated for new settings page integration * Enhanced test coverage for error scenarios * Better mock state management - McpFormModal.test.tsx (60 lines): * Extensive updates for form refactoring * New test cases for multi-app selection * Enhanced validation testing * Better coverage of stdio/http server types - ProviderList.test.tsx (11 lines): * Updated for new card layout * Enhanced drag-and-drop testing - SettingsDialog.test.tsx (96 lines): * Major updates for SettingsPage migration * New test cases for auto-launch functionality * Enhanced integration test coverage * Better async operation testing Hook Tests: - useDirectorySettings.test.tsx (32 lines): * Updated for refactored hook logic * Enhanced test coverage for edge cases - useDragSort.test.tsx (36 lines): * Simplified test cases * Better mock implementation * Improved assertions - useImportExport tests (16 lines total): * Updated for new error handling * Enhanced test coverage - useMcpValidation.test.tsx (23 lines): * Updated validation test cases * Better coverage of error scenarios - useProviderActions.test.tsx (48 lines): * Extensive updates for hook refactoring * New test cases for provider operations * Enhanced mock data - useSettings.test.tsx (12 lines): * New test cases for auto-launch * Enhanced settings state testing * Better async operation coverage Integration Tests: - App.test.tsx (41 lines): * Updated for new routing logic * Enhanced navigation testing * Better component integration coverage - SettingsDialog.test.tsx (88 lines): * Complete rewrite for SettingsPage * New integration test scenarios * Enhanced user workflow testing Mock Infrastructure: - handlers.ts (117 lines): * Major updates for MSW handlers * New handlers for auto-launch commands * Enhanced error simulation * Better request/response mocking - state.ts (37 lines): * Updated mock state structure * New state for auto-launch * Enhanced state reset functionality - tauriMocks.ts (10 lines): * Updated mock implementations * Better type safety - server.ts & testQueryClient.ts: * Minor cleanup (2 lines removed) Test Infrastructure Improvements: - Better test isolation - Enhanced mock data consistency - Improved async operation testing - Better error scenario coverage - Enhanced integration test patterns Coverage Improvements: - Net increase of 195 lines of test code - Better coverage of edge cases - Enhanced error path testing - Improved integration test scenarios - Better mock infrastructure All tests now pass with the refactored components while maintaining comprehensive coverage of functionality and edge cases.
2025-11-21 11:12:06 +08:00
expect(configTextarea.value).toBe(
'{\n "type": "stdio",\n "command": "preset-cmd"\n}',
);
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("提交时清洗字段并调用 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"));
test: update test suites to match component refactoring Comprehensive test updates to align with recent component refactoring and new auto-launch functionality. Component Tests: - AddProviderDialog.test.tsx (10 lines): * Updated test cases for new dialog behavior * Enhanced mock data for preset selection * Improved assertions for validation - ImportExportSection.test.tsx (16 lines): * Updated for new settings page integration * Enhanced test coverage for error scenarios * Better mock state management - McpFormModal.test.tsx (60 lines): * Extensive updates for form refactoring * New test cases for multi-app selection * Enhanced validation testing * Better coverage of stdio/http server types - ProviderList.test.tsx (11 lines): * Updated for new card layout * Enhanced drag-and-drop testing - SettingsDialog.test.tsx (96 lines): * Major updates for SettingsPage migration * New test cases for auto-launch functionality * Enhanced integration test coverage * Better async operation testing Hook Tests: - useDirectorySettings.test.tsx (32 lines): * Updated for refactored hook logic * Enhanced test coverage for edge cases - useDragSort.test.tsx (36 lines): * Simplified test cases * Better mock implementation * Improved assertions - useImportExport tests (16 lines total): * Updated for new error handling * Enhanced test coverage - useMcpValidation.test.tsx (23 lines): * Updated validation test cases * Better coverage of error scenarios - useProviderActions.test.tsx (48 lines): * Extensive updates for hook refactoring * New test cases for provider operations * Enhanced mock data - useSettings.test.tsx (12 lines): * New test cases for auto-launch * Enhanced settings state testing * Better async operation coverage Integration Tests: - App.test.tsx (41 lines): * Updated for new routing logic * Enhanced navigation testing * Better component integration coverage - SettingsDialog.test.tsx (88 lines): * Complete rewrite for SettingsPage * New integration test scenarios * Enhanced user workflow testing Mock Infrastructure: - handlers.ts (117 lines): * Major updates for MSW handlers * New handlers for auto-launch commands * Enhanced error simulation * Better request/response mocking - state.ts (37 lines): * Updated mock state structure * New state for auto-launch * Enhanced state reset functionality - tauriMocks.ts (10 lines): * Updated mock implementations * Better type safety - server.ts & testQueryClient.ts: * Minor cleanup (2 lines removed) Test Infrastructure Improvements: - Better test isolation - Enhanced mock data consistency - Improved async operation testing - Better error scenario coverage - Enhanced integration test patterns Coverage Improvements: - Net increase of 195 lines of test code - Better coverage of edge cases - Enhanced error path testing - Improved integration test scenarios - Better mock infrastructure All tests now pass with the refactored components while maintaining comprehensive coverage of functionality and edge cases.
2025-11-21 11:12:06 +08:00
fireEvent.change(
screen.getByPlaceholderText("mcp.form.descriptionPlaceholder"),
{
target: { value: " Description " },
},
);
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.tagsPlaceholder"), {
target: { value: " tag1 , tag2 " },
});
test: update test suites to match component refactoring Comprehensive test updates to align with recent component refactoring and new auto-launch functionality. Component Tests: - AddProviderDialog.test.tsx (10 lines): * Updated test cases for new dialog behavior * Enhanced mock data for preset selection * Improved assertions for validation - ImportExportSection.test.tsx (16 lines): * Updated for new settings page integration * Enhanced test coverage for error scenarios * Better mock state management - McpFormModal.test.tsx (60 lines): * Extensive updates for form refactoring * New test cases for multi-app selection * Enhanced validation testing * Better coverage of stdio/http server types - ProviderList.test.tsx (11 lines): * Updated for new card layout * Enhanced drag-and-drop testing - SettingsDialog.test.tsx (96 lines): * Major updates for SettingsPage migration * New test cases for auto-launch functionality * Enhanced integration test coverage * Better async operation testing Hook Tests: - useDirectorySettings.test.tsx (32 lines): * Updated for refactored hook logic * Enhanced test coverage for edge cases - useDragSort.test.tsx (36 lines): * Simplified test cases * Better mock implementation * Improved assertions - useImportExport tests (16 lines total): * Updated for new error handling * Enhanced test coverage - useMcpValidation.test.tsx (23 lines): * Updated validation test cases * Better coverage of error scenarios - useProviderActions.test.tsx (48 lines): * Extensive updates for hook refactoring * New test cases for provider operations * Enhanced mock data - useSettings.test.tsx (12 lines): * New test cases for auto-launch * Enhanced settings state testing * Better async operation coverage Integration Tests: - App.test.tsx (41 lines): * Updated for new routing logic * Enhanced navigation testing * Better component integration coverage - SettingsDialog.test.tsx (88 lines): * Complete rewrite for SettingsPage * New integration test scenarios * Enhanced user workflow testing Mock Infrastructure: - handlers.ts (117 lines): * Major updates for MSW handlers * New handlers for auto-launch commands * Enhanced error simulation * Better request/response mocking - state.ts (37 lines): * Updated mock state structure * New state for auto-launch * Enhanced state reset functionality - tauriMocks.ts (10 lines): * Updated mock implementations * Better type safety - server.ts & testQueryClient.ts: * Minor cleanup (2 lines removed) Test Infrastructure Improvements: - Better test isolation - Enhanced mock data consistency - Improved async operation testing - Better error scenario coverage - Enhanced integration test patterns Coverage Improvements: - Net increase of 195 lines of test code - Better coverage of edge cases - Enhanced error path testing - Improved integration test scenarios - Better mock infrastructure All tests now pass with the refactored components while maintaining comprehensive coverage of functionality and edge cases.
2025-11-21 11:12:06 +08:00
fireEvent.change(
screen.getByPlaceholderText("mcp.form.homepagePlaceholder"),
{
target: { value: " https://example.com " },
},
);
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.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 () => {
feat: add model configuration support and fix Gemini deeplink bug (#251) * feat(providers): add notes field for provider management - Add notes field to Provider model (backend and frontend) - Display notes with higher priority than URL in provider card - Style notes as non-clickable text to differentiate from URLs - Add notes input field in provider form - Add i18n support (zh/en) for notes field * chore: format code and clean up unused props - Run cargo fmt on Rust backend code - Format TypeScript imports and code style - Remove unused appId prop from ProviderPresetSelector - Clean up unused variables in tests - Integrate notes field handling in provider dialogs * feat(deeplink): implement ccswitch:// protocol for provider import Add deep link support to enable one-click provider configuration import via ccswitch:// URLs. Backend: - Implement URL parsing and validation (src-tauri/src/deeplink.rs) - Add Tauri commands for parse and import (src-tauri/src/commands/deeplink.rs) - Register ccswitch:// protocol in macOS Info.plist - Add comprehensive unit tests (src-tauri/tests/deeplink_import.rs) Frontend: - Create confirmation dialog with security review UI (src/components/DeepLinkImportDialog.tsx) - Add API wrapper (src/lib/api/deeplink.ts) - Integrate event listeners in App.tsx Configuration: - Update Tauri config for deep link handling - Add i18n support for Chinese and English - Include test page for deep link validation (deeplink-test.html) Files: 15 changed, 1312 insertions(+) * chore(deeplink): integrate deep link handling into app lifecycle Wire up deep link infrastructure with app initialization and event handling. Backend Integration: - Register deep link module and commands in mod.rs - Add URL handling in app setup (src-tauri/src/lib.rs:handle_deeplink_url) - Handle deep links from single instance callback (Windows/Linux CLI) - Handle deep links from macOS system events - Add tauri-plugin-deep-link dependency (Cargo.toml) Frontend Integration: - Listen for deeplink-import/deeplink-error events in App.tsx - Update DeepLinkImportDialog component imports Configuration: - Enable deep link plugin in tauri.conf.json - Update Cargo.lock for new dependencies Localization: - Add Chinese translations for deep link UI (zh.json) - Add English translations for deep link UI (en.json) Files: 9 changed, 359 insertions(+), 18 deletions(-) * refactor(deeplink): enhance Codex provider template generation Align deep link import with UI preset generation logic by: - Adding complete config.toml template matching frontend defaults - Generating safe provider name from sanitized input - Including model_provider, reasoning_effort, and wire_api settings - Removing minimal template that only contained base_url - Cleaning up deprecated test file deeplink-test.html * style: fix clippy uninlined_format_args warnings Apply clippy --fix to use inline format arguments in: - src/mcp.rs (8 fixes) - src/services/env_manager.rs (10 fixes) * style: apply code formatting and cleanup - Format TypeScript files with Prettier (App.tsx, EnvWarningBanner.tsx, formatters.ts) - Organize Rust imports and module order alphabetically - Add newline at end of JSON files (en.json, zh.json) - Update Cargo.lock for dependency changes * feat: add model name configuration support for Codex and fix Gemini model handling - Add visual model name input field for Codex providers - Add model name extraction and update utilities in providerConfigUtils - Implement model name state management in useCodexConfigState hook - Add conditional model field rendering in CodexFormFields (non-official only) - Integrate model name sync with TOML config in ProviderForm - Fix Gemini deeplink model injection bug - Correct environment variable name from GOOGLE_GEMINI_MODEL to GEMINI_MODEL - Add test cases for Gemini model injection (with/without model) - All tests passing (9/9) - Fix Gemini model field binding in edit mode - Add geminiModel state to useGeminiConfigState hook - Extract model value during initialization and reset - Sync model field with geminiEnv state to prevent data loss on submit - Fix missing model value display when editing Gemini providers Changes: - 6 files changed, 245 insertions(+), 13 deletions(-)
2025-11-19 09:03:18 +08:00
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;
test: update test suites to match component refactoring Comprehensive test updates to align with recent component refactoring and new auto-launch functionality. Component Tests: - AddProviderDialog.test.tsx (10 lines): * Updated test cases for new dialog behavior * Enhanced mock data for preset selection * Improved assertions for validation - ImportExportSection.test.tsx (16 lines): * Updated for new settings page integration * Enhanced test coverage for error scenarios * Better mock state management - McpFormModal.test.tsx (60 lines): * Extensive updates for form refactoring * New test cases for multi-app selection * Enhanced validation testing * Better coverage of stdio/http server types - ProviderList.test.tsx (11 lines): * Updated for new card layout * Enhanced drag-and-drop testing - SettingsDialog.test.tsx (96 lines): * Major updates for SettingsPage migration * New test cases for auto-launch functionality * Enhanced integration test coverage * Better async operation testing Hook Tests: - useDirectorySettings.test.tsx (32 lines): * Updated for refactored hook logic * Enhanced test coverage for edge cases - useDragSort.test.tsx (36 lines): * Simplified test cases * Better mock implementation * Improved assertions - useImportExport tests (16 lines total): * Updated for new error handling * Enhanced test coverage - useMcpValidation.test.tsx (23 lines): * Updated validation test cases * Better coverage of error scenarios - useProviderActions.test.tsx (48 lines): * Extensive updates for hook refactoring * New test cases for provider operations * Enhanced mock data - useSettings.test.tsx (12 lines): * New test cases for auto-launch * Enhanced settings state testing * Better async operation coverage Integration Tests: - App.test.tsx (41 lines): * Updated for new routing logic * Enhanced navigation testing * Better component integration coverage - SettingsDialog.test.tsx (88 lines): * Complete rewrite for SettingsPage * New integration test scenarios * Enhanced user workflow testing Mock Infrastructure: - handlers.ts (117 lines): * Major updates for MSW handlers * New handlers for auto-launch commands * Enhanced error simulation * Better request/response mocking - state.ts (37 lines): * Updated mock state structure * New state for auto-launch * Enhanced state reset functionality - tauriMocks.ts (10 lines): * Updated mock implementations * Better type safety - server.ts & testQueryClient.ts: * Minor cleanup (2 lines removed) Test Infrastructure Improvements: - Better test isolation - Enhanced mock data consistency - Improved async operation testing - Better error scenario coverage - Enhanced integration test patterns Coverage Improvements: - Net increase of 195 lines of test code - Better coverage of edge cases - Enhanced error path testing - Improved integration test scenarios - Better mock infrastructure All tests now pass with the refactored components while maintaining comprehensive coverage of functionality and edge cases.
2025-11-21 11:12:06 +08:00
expect(configTextarea.value).toBe(
'{"type":"stdio","command":"wizard-cmd"}',
);
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("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 () => {
feat: add model configuration support and fix Gemini deeplink bug (#251) * feat(providers): add notes field for provider management - Add notes field to Provider model (backend and frontend) - Display notes with higher priority than URL in provider card - Style notes as non-clickable text to differentiate from URLs - Add notes input field in provider form - Add i18n support (zh/en) for notes field * chore: format code and clean up unused props - Run cargo fmt on Rust backend code - Format TypeScript imports and code style - Remove unused appId prop from ProviderPresetSelector - Clean up unused variables in tests - Integrate notes field handling in provider dialogs * feat(deeplink): implement ccswitch:// protocol for provider import Add deep link support to enable one-click provider configuration import via ccswitch:// URLs. Backend: - Implement URL parsing and validation (src-tauri/src/deeplink.rs) - Add Tauri commands for parse and import (src-tauri/src/commands/deeplink.rs) - Register ccswitch:// protocol in macOS Info.plist - Add comprehensive unit tests (src-tauri/tests/deeplink_import.rs) Frontend: - Create confirmation dialog with security review UI (src/components/DeepLinkImportDialog.tsx) - Add API wrapper (src/lib/api/deeplink.ts) - Integrate event listeners in App.tsx Configuration: - Update Tauri config for deep link handling - Add i18n support for Chinese and English - Include test page for deep link validation (deeplink-test.html) Files: 15 changed, 1312 insertions(+) * chore(deeplink): integrate deep link handling into app lifecycle Wire up deep link infrastructure with app initialization and event handling. Backend Integration: - Register deep link module and commands in mod.rs - Add URL handling in app setup (src-tauri/src/lib.rs:handle_deeplink_url) - Handle deep links from single instance callback (Windows/Linux CLI) - Handle deep links from macOS system events - Add tauri-plugin-deep-link dependency (Cargo.toml) Frontend Integration: - Listen for deeplink-import/deeplink-error events in App.tsx - Update DeepLinkImportDialog component imports Configuration: - Enable deep link plugin in tauri.conf.json - Update Cargo.lock for new dependencies Localization: - Add Chinese translations for deep link UI (zh.json) - Add English translations for deep link UI (en.json) Files: 9 changed, 359 insertions(+), 18 deletions(-) * refactor(deeplink): enhance Codex provider template generation Align deep link import with UI preset generation logic by: - Adding complete config.toml template matching frontend defaults - Generating safe provider name from sanitized input - Including model_provider, reasoning_effort, and wire_api settings - Removing minimal template that only contained base_url - Cleaning up deprecated test file deeplink-test.html * style: fix clippy uninlined_format_args warnings Apply clippy --fix to use inline format arguments in: - src/mcp.rs (8 fixes) - src/services/env_manager.rs (10 fixes) * style: apply code formatting and cleanup - Format TypeScript files with Prettier (App.tsx, EnvWarningBanner.tsx, formatters.ts) - Organize Rust imports and module order alphabetically - Add newline at end of JSON files (en.json, zh.json) - Update Cargo.lock for dependency changes * feat: add model name configuration support for Codex and fix Gemini model handling - Add visual model name input field for Codex providers - Add model name extraction and update utilities in providerConfigUtils - Implement model name state management in useCodexConfigState hook - Add conditional model field rendering in CodexFormFields (non-official only) - Integrate model name sync with TOML config in ProviderForm - Fix Gemini deeplink model injection bug - Correct environment variable name from GOOGLE_GEMINI_MODEL to GEMINI_MODEL - Add test cases for Gemini model injection (with/without model) - All tests passing (9/9) - Fix Gemini model field binding in edit mode - Add geminiModel state to useGeminiConfigState hook - Extract model value during initialization and reset - Sync model field with geminiEnv state to prevent data loss on submit - Fix missing model value display when editing Gemini providers Changes: - 6 files changed, 245 insertions(+), 13 deletions(-)
2025-11-19 09:03:18 +08:00
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;
test: update test suites to match component refactoring Comprehensive test updates to align with recent component refactoring and new auto-launch functionality. Component Tests: - AddProviderDialog.test.tsx (10 lines): * Updated test cases for new dialog behavior * Enhanced mock data for preset selection * Improved assertions for validation - ImportExportSection.test.tsx (16 lines): * Updated for new settings page integration * Enhanced test coverage for error scenarios * Better mock state management - McpFormModal.test.tsx (60 lines): * Extensive updates for form refactoring * New test cases for multi-app selection * Enhanced validation testing * Better coverage of stdio/http server types - ProviderList.test.tsx (11 lines): * Updated for new card layout * Enhanced drag-and-drop testing - SettingsDialog.test.tsx (96 lines): * Major updates for SettingsPage migration * New test cases for auto-launch functionality * Enhanced integration test coverage * Better async operation testing Hook Tests: - useDirectorySettings.test.tsx (32 lines): * Updated for refactored hook logic * Enhanced test coverage for edge cases - useDragSort.test.tsx (36 lines): * Simplified test cases * Better mock implementation * Improved assertions - useImportExport tests (16 lines total): * Updated for new error handling * Enhanced test coverage - useMcpValidation.test.tsx (23 lines): * Updated validation test cases * Better coverage of error scenarios - useProviderActions.test.tsx (48 lines): * Extensive updates for hook refactoring * New test cases for provider operations * Enhanced mock data - useSettings.test.tsx (12 lines): * New test cases for auto-launch * Enhanced settings state testing * Better async operation coverage Integration Tests: - App.test.tsx (41 lines): * Updated for new routing logic * Enhanced navigation testing * Better component integration coverage - SettingsDialog.test.tsx (88 lines): * Complete rewrite for SettingsPage * New integration test scenarios * Enhanced user workflow testing Mock Infrastructure: - handlers.ts (117 lines): * Major updates for MSW handlers * New handlers for auto-launch commands * Enhanced error simulation * Better request/response mocking - state.ts (37 lines): * Updated mock state structure * New state for auto-launch * Enhanced state reset functionality - tauriMocks.ts (10 lines): * Updated mock implementations * Better type safety - server.ts & testQueryClient.ts: * Minor cleanup (2 lines removed) Test Infrastructure Improvements: - Better test isolation - Enhanced mock data consistency - Improved async operation testing - Better error scenario coverage - Enhanced integration test patterns Coverage Improvements: - Net increase of 195 lines of test code - Better coverage of edge cases - Enhanced error path testing - Improved integration test scenarios - Better mock infrastructure All tests now pass with the refactored components while maintaining comprehensive coverage of functionality and edge cases.
2025-11-21 11:12:06 +08:00
expect(configTextarea.value).toContain('"command": "old"');
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
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);
});
});