import { beforeEach, describe, expect, it, vi } from "vitest"; import { renderHook, waitFor } from "@testing-library/react"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import type { ReactNode } from "react"; import { fetchColonyInspections } from "./api"; import { useLastInspection } from "./use-last-inspection"; import { listPacks } from "@/lib/apiaries/offline-pack"; import { offlinePack, packColony, packInspection, storedPack, } from "@/lib/apiaries/offline-pack.fixtures"; import type { Inspection } from "./types"; vi.mock("./api", () => ({ fetchColonyInspections: vi.fn() })); vi.mock("@/lib/auth/auth-context", () => ({ useCurrentUserId: () => "user-1" })); vi.mock("@/lib/apiaries/offline-pack", async (importOriginal) => ({ ...(await importOriginal()), listPacks: vi.fn(), })); function day(isoDay: string): string { return `${isoDay}T00:00:00.000Z`; } function renderLastInspection(client: QueryClient) { const wrapper = ({ children }: { children: ReactNode }) => ( {children} ); return renderHook(() => useLastInspection("colony-1"), { wrapper }); } function newClient() { return new QueryClient({ defaultOptions: { queries: { retry: false } } }); } describe("useLastInspection", () => { beforeEach(() => { vi.mocked(fetchColonyInspections).mockReset(); vi.mocked(listPacks).mockReset().mockResolvedValue([]); }); it("takes the newest inspection the server has", async () => { vi.mocked(fetchColonyInspections).mockResolvedValue([ { ...packInspection("old", "colony-1", day("2026-09-01")), userId: "u" }, { ...packInspection("new", "colony-1", day("2026-10-01")), userId: "u" }, ]); const { result } = renderLastInspection(newClient()); await waitFor(() => expect(result.current.inspection?.id).toBe("new")); expect(listPacks).not.toHaveBeenCalled(); }); it("reads the last inspection from the loaded pack while offline", async () => { vi.mocked(fetchColonyInspections).mockRejectedValue(new TypeError("Failed to fetch")); vi.mocked(listPacks).mockResolvedValue([ storedPack( offlinePack({ colonies: [packColony("colony-1", "A1")], inspections: [ packInspection("p-old", "colony-1", day("2026-09-20")), packInspection("p-new", "colony-1", day("2026-10-02")), packInspection("other", "colony-2", day("2026-10-05")), ], }), ), ]); const { result } = renderLastInspection(newClient()); await waitFor(() => expect(result.current.inspection?.id).toBe("p-new")); expect(result.current.isLoading).toBe(false); }); it("shows the colony page's inspections at once while it asks the server again", async () => { vi.mocked(fetchColonyInspections).mockReturnValue(new Promise(() => undefined)); const client = newClient(); client.setQueryData( ["colonies", "colony-1", "inspections"], [{ ...packInspection("cached", "colony-1", day("2026-10-01")), userId: "u" }], ); const { result } = renderLastInspection(client); expect(result.current.inspection?.id).toBe("cached"); expect(result.current.isLoading).toBe(false); }); });