import { act, renderHook } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { useSiteDialogState } from "@/app/(protected)/workorders/_components/list/table/cells/use-site-dialog-state"; import type { Location } from "@/domain/locations/types/location"; import type { LocationOption } from "@/domain/work-orders/types/work-order"; const detailById = new Map(); vi.mock("@/domain/locations/use-cases/use-location-detail", () => ({ useLocationDetail: (id: string | undefined) => ({ data: id && detailById.has(id) ? detailById.get(id) : undefined, isLoading: Boolean(id && !detailById.has(id)), isError: false, }), })); const SITES: LocationOption[] = [ { id: "loc-1", name: "BK5 · Dallas", siteCode: "BK5", city: "Dallas", state: "TX" }, { id: "loc-2", name: "SEA1 · Seattle", siteCode: "SEA1", city: "Seattle", state: "WA" }, ]; function locationDetail(id: string, contact: string, phone: string): Location { return { id, name: id, contact, phone, address: "100 Main St", city: "Dallas", state: "TX", zipCode: "75001", }; } function renderSiteDialogState() { return renderHook(() => useSiteDialogState({ open: true, onOpenChange: vi.fn(), value: "", locationId: "", pocName: "", pocPhone: "", pocNotes: "", additionalContacts: [], sites: SITES, createMode: true, onSave: vi.fn(), }), ); } describe("useSiteDialogState POC autofill", () => { beforeEach(() => { detailById.clear(); }); it("preserves POC typed before deferred location detail resolves", () => { const { result, rerender } = renderSiteDialogState(); act(() => { result.current.handlePick("loc-1"); }); act(() => { result.current.setPn("Dispatcher Typed"); result.current.setPp("999-000-1111"); }); expect(result.current.pn).toBe("Dispatcher Typed"); expect(result.current.pp).toBe("999-000-1111"); detailById.set("loc-1", locationDetail("loc-1", "Site Contact", "214-555-0111")); act(() => { rerender(); }); expect(result.current.pn).toBe("Dispatcher Typed"); expect(result.current.pp).toBe("999-000-1111"); }); it("clears prior POC on site switch then autofills from the new site detail", () => { const { result, rerender } = renderSiteDialogState(); act(() => { result.current.handlePick("loc-1"); }); detailById.set("loc-1", locationDetail("loc-1", "Contact A", "111-111-1111")); act(() => { rerender(); }); expect(result.current.pn).toBe("Contact A"); expect(result.current.pp).toBe("111-111-1111"); act(() => { result.current.handlePick("loc-2"); }); expect(result.current.locId).toBe("loc-2"); expect(result.current.pn).toBe(""); expect(result.current.pp).toBe(""); detailById.set("loc-2", locationDetail("loc-2", "Contact B", "222-222-2222")); act(() => { rerender(); }); expect(result.current.pn).toBe("Contact B"); expect(result.current.pp).toBe("222-222-2222"); }); });