Files
cc-switch/tests/hooks/useSettingsForm.test.tsx
Jason c2031c9b5c 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

171 lines
5.0 KiB
TypeScript

import { renderHook, act, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import i18n from "i18next";
import { useSettingsForm } from "@/hooks/useSettingsForm";
const useSettingsQueryMock = vi.fn();
vi.mock("@/lib/query", () => ({
useSettingsQuery: (...args: unknown[]) => useSettingsQueryMock(...args),
}));
let changeLanguageSpy: ReturnType<typeof vi.spyOn<any, any>>;
beforeEach(() => {
useSettingsQueryMock.mockReset();
window.localStorage.clear();
(i18n as any).language = "zh";
changeLanguageSpy = vi
.spyOn(i18n, "changeLanguage")
.mockImplementation(async (lang?: string) => {
(i18n as any).language = lang;
return i18n.t;
});
});
afterEach(() => {
changeLanguageSpy.mockRestore();
});
describe("useSettingsForm Hook", () => {
it("should normalize settings and sync language on initialization", async () => {
useSettingsQueryMock.mockReturnValue({
data: {
showInTray: undefined,
minimizeToTrayOnClose: undefined,
enableClaudePluginIntegration: undefined,
claudeConfigDir: " /Users/demo ",
codexConfigDir: " ",
language: "en",
},
isLoading: false,
});
const { result } = renderHook(() => useSettingsForm());
await waitFor(() => {
expect(result.current.settings).not.toBeNull();
});
const settings = result.current.settings!;
expect(settings.showInTray).toBe(true);
expect(settings.minimizeToTrayOnClose).toBe(true);
expect(settings.enableClaudePluginIntegration).toBe(false);
expect(settings.claudeConfigDir).toBe("/Users/demo");
expect(settings.codexConfigDir).toBeUndefined();
expect(settings.language).toBe("en");
expect(result.current.initialLanguage).toBe("en");
expect(changeLanguageSpy).toHaveBeenCalledWith("en");
});
it("should prioritize reading language from local storage in readPersistedLanguage", () => {
useSettingsQueryMock.mockReturnValue({
data: null,
isLoading: false,
});
window.localStorage.setItem("language", "en");
const { result } = renderHook(() => useSettingsForm());
const lang = result.current.readPersistedLanguage();
expect(lang).toBe("en");
expect(changeLanguageSpy).not.toHaveBeenCalled();
});
it("should update fields and sync language when language changes in updateSettings", () => {
useSettingsQueryMock.mockReturnValue({
data: null,
isLoading: false,
});
const { result } = renderHook(() => useSettingsForm());
act(() => {
result.current.updateSettings({ showInTray: false });
});
expect(result.current.settings?.showInTray).toBe(false);
changeLanguageSpy.mockClear();
act(() => {
result.current.updateSettings({ language: "en" });
});
expect(result.current.settings?.language).toBe("en");
expect(changeLanguageSpy).toHaveBeenCalledWith("en");
});
it("should reset with server data and restore initial language in resetSettings", async () => {
useSettingsQueryMock.mockReturnValue({
data: {
showInTray: true,
minimizeToTrayOnClose: true,
enableClaudePluginIntegration: false,
claudeConfigDir: "/origin",
codexConfigDir: null,
language: "en",
},
isLoading: false,
});
const { result } = renderHook(() => useSettingsForm());
await waitFor(() => {
expect(result.current.settings).not.toBeNull();
});
changeLanguageSpy.mockClear();
(i18n as any).language = "zh";
act(() => {
result.current.resetSettings({
showInTray: false,
minimizeToTrayOnClose: false,
enableClaudePluginIntegration: true,
claudeConfigDir: " /reset ",
codexConfigDir: " ",
language: "zh",
});
});
const settings = result.current.settings!;
expect(settings.showInTray).toBe(false);
expect(settings.minimizeToTrayOnClose).toBe(false);
expect(settings.enableClaudePluginIntegration).toBe(true);
expect(settings.claudeConfigDir).toBe("/reset");
expect(settings.codexConfigDir).toBeUndefined();
expect(settings.language).toBe("zh");
expect(result.current.initialLanguage).toBe("en");
expect(changeLanguageSpy).toHaveBeenCalledWith("en");
});
it("should not call changeLanguage repeatedly when language is consistent in syncLanguage", async () => {
useSettingsQueryMock.mockReturnValue({
data: {
showInTray: true,
minimizeToTrayOnClose: true,
enableClaudePluginIntegration: false,
claudeConfigDir: null,
codexConfigDir: null,
language: "zh",
},
isLoading: false,
});
const { result } = renderHook(() => useSettingsForm());
await waitFor(() => {
expect(result.current.settings).not.toBeNull();
});
changeLanguageSpy.mockClear();
(i18n as any).language = "zh";
act(() => {
result.current.syncLanguage("zh");
});
expect(changeLanguageSpy).not.toHaveBeenCalled();
});
});