Files
cc-switch/tests/hooks/useImportExport.test.tsx

255 lines
7.7 KiB
TypeScript
Raw Normal View History

test: add comprehensive tests for hooks and components Add extensive unit and component tests covering import/export, settings, and provider list functionality, advancing to Sprint 2 of test development. Hook Tests: - useImportExport (11 tests): * File selection success/failure flows * Import process with success/failure/exception paths * Export functionality with error handling * User cancellation scenarios * State management (clear selection, reset status) * Fake timers for async callback testing - useSettingsForm (5 tests): * Settings normalization on initialization * Language persistence from localStorage * Field updates with language sync * Reset functionality with initial language restoration * Optimization to avoid redundant language changes Component Tests: - ProviderList (3 tests): * Loading state with skeleton placeholders * Empty state with create callback * Render order from useDragSort with action callbacks * Props pass-through (isCurrent, isEditMode, dragHandleProps) * Mock ProviderCard to isolate component under test Technical Highlights: - Fake timers (vi.useFakeTimers) for async control - i18n mock with changeLanguage spy - Partial mock of @dnd-kit/sortable using vi.importActual - ProviderCard render spy for props verification - Comprehensive error handling coverage Test Coverage: ✓ 19 new test cases (11 + 5 + 3) ✓ Total: 35 tests passing ✓ Execution time: 865ms ✓ TypeScript: 0 errors Related: Import/export, settings management, provider list rendering Sprint Progress: Sprint 1 complete, Sprint 2 in progress (component tests)
2025-10-25 11:16:38 +08:00
import { renderHook, act } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { useImportExport } from "@/hooks/useImportExport";
const toastSuccessMock = vi.fn();
const toastErrorMock = vi.fn();
const toastWarningMock = vi.fn();
test: add comprehensive tests for hooks and components Add extensive unit and component tests covering import/export, settings, and provider list functionality, advancing to Sprint 2 of test development. Hook Tests: - useImportExport (11 tests): * File selection success/failure flows * Import process with success/failure/exception paths * Export functionality with error handling * User cancellation scenarios * State management (clear selection, reset status) * Fake timers for async callback testing - useSettingsForm (5 tests): * Settings normalization on initialization * Language persistence from localStorage * Field updates with language sync * Reset functionality with initial language restoration * Optimization to avoid redundant language changes Component Tests: - ProviderList (3 tests): * Loading state with skeleton placeholders * Empty state with create callback * Render order from useDragSort with action callbacks * Props pass-through (isCurrent, isEditMode, dragHandleProps) * Mock ProviderCard to isolate component under test Technical Highlights: - Fake timers (vi.useFakeTimers) for async control - i18n mock with changeLanguage spy - Partial mock of @dnd-kit/sortable using vi.importActual - ProviderCard render spy for props verification - Comprehensive error handling coverage Test Coverage: ✓ 19 new test cases (11 + 5 + 3) ✓ Total: 35 tests passing ✓ Execution time: 865ms ✓ TypeScript: 0 errors Related: Import/export, settings management, provider list rendering Sprint Progress: Sprint 1 complete, Sprint 2 in progress (component tests)
2025-10-25 11:16:38 +08:00
vi.mock("sonner", () => ({
toast: {
success: (...args: unknown[]) => toastSuccessMock(...args),
error: (...args: unknown[]) => toastErrorMock(...args),
warning: (...args: unknown[]) => toastWarningMock(...args),
test: add comprehensive tests for hooks and components Add extensive unit and component tests covering import/export, settings, and provider list functionality, advancing to Sprint 2 of test development. Hook Tests: - useImportExport (11 tests): * File selection success/failure flows * Import process with success/failure/exception paths * Export functionality with error handling * User cancellation scenarios * State management (clear selection, reset status) * Fake timers for async callback testing - useSettingsForm (5 tests): * Settings normalization on initialization * Language persistence from localStorage * Field updates with language sync * Reset functionality with initial language restoration * Optimization to avoid redundant language changes Component Tests: - ProviderList (3 tests): * Loading state with skeleton placeholders * Empty state with create callback * Render order from useDragSort with action callbacks * Props pass-through (isCurrent, isEditMode, dragHandleProps) * Mock ProviderCard to isolate component under test Technical Highlights: - Fake timers (vi.useFakeTimers) for async control - i18n mock with changeLanguage spy - Partial mock of @dnd-kit/sortable using vi.importActual - ProviderCard render spy for props verification - Comprehensive error handling coverage Test Coverage: ✓ 19 new test cases (11 + 5 + 3) ✓ Total: 35 tests passing ✓ Execution time: 865ms ✓ TypeScript: 0 errors Related: Import/export, settings management, provider list rendering Sprint Progress: Sprint 1 complete, Sprint 2 in progress (component tests)
2025-10-25 11:16:38 +08:00
},
}));
const openFileDialogMock = vi.fn();
const importConfigMock = vi.fn();
const saveFileDialogMock = vi.fn();
const exportConfigMock = vi.fn();
const syncCurrentProvidersLiveMock = vi.fn();
test: add comprehensive tests for hooks and components Add extensive unit and component tests covering import/export, settings, and provider list functionality, advancing to Sprint 2 of test development. Hook Tests: - useImportExport (11 tests): * File selection success/failure flows * Import process with success/failure/exception paths * Export functionality with error handling * User cancellation scenarios * State management (clear selection, reset status) * Fake timers for async callback testing - useSettingsForm (5 tests): * Settings normalization on initialization * Language persistence from localStorage * Field updates with language sync * Reset functionality with initial language restoration * Optimization to avoid redundant language changes Component Tests: - ProviderList (3 tests): * Loading state with skeleton placeholders * Empty state with create callback * Render order from useDragSort with action callbacks * Props pass-through (isCurrent, isEditMode, dragHandleProps) * Mock ProviderCard to isolate component under test Technical Highlights: - Fake timers (vi.useFakeTimers) for async control - i18n mock with changeLanguage spy - Partial mock of @dnd-kit/sortable using vi.importActual - ProviderCard render spy for props verification - Comprehensive error handling coverage Test Coverage: ✓ 19 new test cases (11 + 5 + 3) ✓ Total: 35 tests passing ✓ Execution time: 865ms ✓ TypeScript: 0 errors Related: Import/export, settings management, provider list rendering Sprint Progress: Sprint 1 complete, Sprint 2 in progress (component tests)
2025-10-25 11:16:38 +08:00
vi.mock("@/lib/api", () => ({
settingsApi: {
openFileDialog: (...args: unknown[]) => openFileDialogMock(...args),
importConfigFromFile: (...args: unknown[]) => importConfigMock(...args),
saveFileDialog: (...args: unknown[]) => saveFileDialogMock(...args),
exportConfigToFile: (...args: unknown[]) => exportConfigMock(...args),
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
syncCurrentProvidersLive: (...args: unknown[]) =>
syncCurrentProvidersLiveMock(...args),
test: add comprehensive tests for hooks and components Add extensive unit and component tests covering import/export, settings, and provider list functionality, advancing to Sprint 2 of test development. Hook Tests: - useImportExport (11 tests): * File selection success/failure flows * Import process with success/failure/exception paths * Export functionality with error handling * User cancellation scenarios * State management (clear selection, reset status) * Fake timers for async callback testing - useSettingsForm (5 tests): * Settings normalization on initialization * Language persistence from localStorage * Field updates with language sync * Reset functionality with initial language restoration * Optimization to avoid redundant language changes Component Tests: - ProviderList (3 tests): * Loading state with skeleton placeholders * Empty state with create callback * Render order from useDragSort with action callbacks * Props pass-through (isCurrent, isEditMode, dragHandleProps) * Mock ProviderCard to isolate component under test Technical Highlights: - Fake timers (vi.useFakeTimers) for async control - i18n mock with changeLanguage spy - Partial mock of @dnd-kit/sortable using vi.importActual - ProviderCard render spy for props verification - Comprehensive error handling coverage Test Coverage: ✓ 19 new test cases (11 + 5 + 3) ✓ Total: 35 tests passing ✓ Execution time: 865ms ✓ TypeScript: 0 errors Related: Import/export, settings management, provider list rendering Sprint Progress: Sprint 1 complete, Sprint 2 in progress (component tests)
2025-10-25 11:16:38 +08:00
},
}));
beforeEach(() => {
openFileDialogMock.mockReset();
importConfigMock.mockReset();
saveFileDialogMock.mockReset();
exportConfigMock.mockReset();
toastSuccessMock.mockReset();
toastErrorMock.mockReset();
toastWarningMock.mockReset();
syncCurrentProvidersLiveMock.mockReset();
test: add comprehensive tests for hooks and components Add extensive unit and component tests covering import/export, settings, and provider list functionality, advancing to Sprint 2 of test development. Hook Tests: - useImportExport (11 tests): * File selection success/failure flows * Import process with success/failure/exception paths * Export functionality with error handling * User cancellation scenarios * State management (clear selection, reset status) * Fake timers for async callback testing - useSettingsForm (5 tests): * Settings normalization on initialization * Language persistence from localStorage * Field updates with language sync * Reset functionality with initial language restoration * Optimization to avoid redundant language changes Component Tests: - ProviderList (3 tests): * Loading state with skeleton placeholders * Empty state with create callback * Render order from useDragSort with action callbacks * Props pass-through (isCurrent, isEditMode, dragHandleProps) * Mock ProviderCard to isolate component under test Technical Highlights: - Fake timers (vi.useFakeTimers) for async control - i18n mock with changeLanguage spy - Partial mock of @dnd-kit/sortable using vi.importActual - ProviderCard render spy for props verification - Comprehensive error handling coverage Test Coverage: ✓ 19 new test cases (11 + 5 + 3) ✓ Total: 35 tests passing ✓ Execution time: 865ms ✓ TypeScript: 0 errors Related: Import/export, settings management, provider list rendering Sprint Progress: Sprint 1 complete, Sprint 2 in progress (component tests)
2025-10-25 11:16:38 +08:00
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
describe("useImportExport Hook", () => {
it("should update state after successfully selecting file", async () => {
openFileDialogMock.mockResolvedValue("/path/config.json");
const { result } = renderHook(() => useImportExport());
await act(async () => {
await result.current.selectImportFile();
});
expect(result.current.selectedFile).toBe("/path/config.json");
expect(result.current.status).toBe("idle");
expect(result.current.errorMessage).toBeNull();
});
it("should show error toast and keep initial state when file dialog fails", async () => {
openFileDialogMock.mockRejectedValue(new Error("file dialog error"));
const { result } = renderHook(() => useImportExport());
await act(async () => {
await result.current.selectImportFile();
});
expect(toastErrorMock).toHaveBeenCalledTimes(1);
expect(result.current.selectedFile).toBe("");
expect(result.current.status).toBe("idle");
});
it("should show error and return early when no file is selected for import", async () => {
const { result } = renderHook(() =>
useImportExport({ onImportSuccess: vi.fn() }),
);
await act(async () => {
await result.current.importConfig();
});
expect(toastErrorMock).toHaveBeenCalledTimes(1);
expect(importConfigMock).not.toHaveBeenCalled();
expect(result.current.status).toBe("idle");
});
it("should set success status, record backup ID, and call callback on successful import", async () => {
openFileDialogMock.mockResolvedValue("/config.json");
importConfigMock.mockResolvedValue({
success: true,
backupId: "backup-123",
});
const onImportSuccess = vi.fn();
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 { result } = renderHook(() => useImportExport({ onImportSuccess }));
test: add comprehensive tests for hooks and components Add extensive unit and component tests covering import/export, settings, and provider list functionality, advancing to Sprint 2 of test development. Hook Tests: - useImportExport (11 tests): * File selection success/failure flows * Import process with success/failure/exception paths * Export functionality with error handling * User cancellation scenarios * State management (clear selection, reset status) * Fake timers for async callback testing - useSettingsForm (5 tests): * Settings normalization on initialization * Language persistence from localStorage * Field updates with language sync * Reset functionality with initial language restoration * Optimization to avoid redundant language changes Component Tests: - ProviderList (3 tests): * Loading state with skeleton placeholders * Empty state with create callback * Render order from useDragSort with action callbacks * Props pass-through (isCurrent, isEditMode, dragHandleProps) * Mock ProviderCard to isolate component under test Technical Highlights: - Fake timers (vi.useFakeTimers) for async control - i18n mock with changeLanguage spy - Partial mock of @dnd-kit/sortable using vi.importActual - ProviderCard render spy for props verification - Comprehensive error handling coverage Test Coverage: ✓ 19 new test cases (11 + 5 + 3) ✓ Total: 35 tests passing ✓ Execution time: 865ms ✓ TypeScript: 0 errors Related: Import/export, settings management, provider list rendering Sprint Progress: Sprint 1 complete, Sprint 2 in progress (component tests)
2025-10-25 11:16:38 +08:00
await act(async () => {
await result.current.selectImportFile();
});
await act(async () => {
await result.current.importConfig();
});
expect(importConfigMock).toHaveBeenCalledWith("/config.json");
expect(result.current.status).toBe("success");
expect(result.current.backupId).toBe("backup-123");
expect(toastSuccessMock).toHaveBeenCalledTimes(1);
// Skip delay to execute callback
await act(async () => {
vi.runOnlyPendingTimers();
});
expect(onImportSuccess).toHaveBeenCalledTimes(1);
});
it("should show error message and keep selected file when import result fails", async () => {
openFileDialogMock.mockResolvedValue("/config.json");
importConfigMock.mockResolvedValue({
success: false,
message: "Config corrupted",
});
const { result } = renderHook(() => useImportExport());
await act(async () => {
await result.current.selectImportFile();
});
await act(async () => {
await result.current.importConfig();
});
expect(result.current.status).toBe("error");
expect(result.current.errorMessage).toBe("Config corrupted");
expect(result.current.selectedFile).toBe("/config.json");
expect(toastErrorMock).toHaveBeenCalledWith("Config corrupted");
});
it("should catch and display error when import process throws exception", async () => {
openFileDialogMock.mockResolvedValue("/config.json");
importConfigMock.mockRejectedValue(new Error("Import failed"));
const { result } = renderHook(() => useImportExport());
await act(async () => {
await result.current.selectImportFile();
});
await act(async () => {
await result.current.importConfig();
});
expect(result.current.status).toBe("error");
expect(result.current.errorMessage).toBe("Import failed");
expect(toastErrorMock).toHaveBeenCalledWith(
expect.stringContaining("导入配置失败:"),
);
});
it("should export successfully with default filename and show path in toast", async () => {
saveFileDialogMock.mockResolvedValue("/export.json");
exportConfigMock.mockResolvedValue({
success: true,
filePath: "/backup/export.json",
});
const { result } = renderHook(() => useImportExport());
await act(async () => {
await result.current.exportConfig();
});
expect(saveFileDialogMock).toHaveBeenCalledTimes(1);
expect(exportConfigMock).toHaveBeenCalledWith("/export.json");
expect(toastSuccessMock).toHaveBeenCalledWith(
expect.stringContaining("/backup/export.json"),
);
});
it("should show error message when export fails", async () => {
saveFileDialogMock.mockResolvedValue("/export.json");
exportConfigMock.mockResolvedValue({
success: false,
message: "Write failed",
});
const { result } = renderHook(() => useImportExport());
await act(async () => {
await result.current.exportConfig();
});
expect(toastErrorMock).toHaveBeenCalledWith(
expect.stringContaining("Write failed"),
);
});
it("should catch and show error when export throws exception", async () => {
saveFileDialogMock.mockResolvedValue("/export.json");
exportConfigMock.mockRejectedValue(new Error("Disk read-only"));
const { result } = renderHook(() => useImportExport());
await act(async () => {
await result.current.exportConfig();
});
expect(toastErrorMock).toHaveBeenCalledWith(
expect.stringContaining("Disk read-only"),
);
});
it("should show error and return when user cancels save dialog during export", async () => {
saveFileDialogMock.mockResolvedValue(null);
const { result } = renderHook(() => useImportExport());
await act(async () => {
await result.current.exportConfig();
});
expect(exportConfigMock).not.toHaveBeenCalled();
expect(toastErrorMock).toHaveBeenCalledTimes(1);
});
it("should restore initial values when clearing selection and resetting status", async () => {
openFileDialogMock.mockResolvedValue("/config.json");
const { result } = renderHook(() => useImportExport());
await act(async () => {
await result.current.selectImportFile();
});
act(() => {
result.current.clearSelection();
});
expect(result.current.selectedFile).toBe("");
expect(result.current.status).toBe("idle");
act(() => {
result.current.resetStatus();
});
expect(result.current.errorMessage).toBeNull();
expect(result.current.backupId).toBeNull();
});
});