// @vitest-environment jsdom import { act, renderHook } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { useOutline } from "./useOutline"; import type { OutlineChapterView } from "@/lib/api/types"; // 后端客户端与 Toast 是 hook 的外部副作用边界,单测一律 mock。 const post = vi.fn(); const toast = vi.fn(); vi.mock("@/lib/api/client", () => ({ api: { POST: (...a: unknown[]) => post(...a) } })); vi.mock("@/components/Toast", () => ({ useToast: () => toast })); function makeChapter(no: number): OutlineChapterView { return { no, volume: 1 }; } describe("useOutline", () => { beforeEach(() => { post.mockReset(); toast.mockReset(); }); afterEach(() => vi.clearAllMocks()); it("空初始:status=idle", () => { const { result } = renderHook(() => useOutline([])); expect(result.current.status).toBe("idle"); expect(result.current.chapters).toEqual([]); expect(result.current.error).toBeNull(); }); it("非空初始:status=ready 并保留章节", () => { const initial = [makeChapter(1)]; const { result } = renderHook(() => useOutline(initial)); expect(result.current.status).toBe("ready"); expect(result.current.chapters).toEqual(initial); }); it("生成成功:status 走到 ready 并填充章节并弹成功 toast", async () => { const chapters = [makeChapter(1), makeChapter(2)]; post.mockResolvedValue({ data: { chapters }, error: null }); const { result } = renderHook(() => useOutline([])); await act(async () => { await result.current.generate("p1", 1); }); expect(result.current.status).toBe("ready"); expect(result.current.chapters).toEqual(chapters); expect(result.current.error).toBeNull(); expect(toast).toHaveBeenCalledWith("大纲已生成", "success"); }); it("data.chapters 为空时章节回退为空数组", async () => { post.mockResolvedValue({ data: { chapters: null }, error: null }); const { result } = renderHook(() => useOutline([])); await act(async () => { await result.current.generate("p1", 1); }); expect(result.current.status).toBe("ready"); expect(result.current.chapters).toEqual([]); }); it("后端返回业务错误:status=error 并 surface 友好文案", async () => { post.mockResolvedValue({ data: null, error: { error: { code: "LLM_UNAVAILABLE" } }, }); const { result } = renderHook(() => useOutline([])); await act(async () => { await result.current.generate("p1", 1); }); expect(result.current.status).toBe("error"); expect(result.current.error?.code).toBe("OUTLINE_FAILED"); expect(result.current.error?.message).toContain("provider"); expect(toast).toHaveBeenCalledWith(expect.any(String), "error"); }); it("data 为空且无 error 也走错误分支", async () => { post.mockResolvedValue({ data: null, error: null }); const { result } = renderHook(() => useOutline([])); await act(async () => { await result.current.generate("p1", 1); }); expect(result.current.status).toBe("error"); expect(result.current.error?.code).toBe("OUTLINE_FAILED"); }); });