// @vitest-environment jsdom import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { renderHook, act } from "@testing-library/react"; import { useSplitPoll } from "./useSplitPoll"; // Split-tender gateway poll loop (Task 13). Fake timers drive the interval/timeout deterministically. beforeEach(() => { vi.useFakeTimers(); }); afterEach(() => { vi.useRealTimers(); vi.clearAllMocks(); }); describe("useSplitPoll", () => { it("does not poll when uuid is null", async () => { const poll = vi.fn().mockResolvedValue({ status: "PENDING" }); renderHook(() => useSplitPoll({ uuid: null, poll, cancel: vi.fn(), onPaid: vi.fn(), onFailed: vi.fn() }), ); await act(async () => { await vi.advanceTimersByTimeAsync(10_000); }); expect(poll).not.toHaveBeenCalled(); }); it("polls and stops on PAID (calls onPaid, not cancel/onFailed)", async () => { const poll = vi.fn().mockResolvedValue({ status: "PAID" }); const cancel = vi.fn().mockResolvedValue(true); const onPaid = vi.fn(); const onFailed = vi.fn(); renderHook(() => useSplitPoll({ uuid: "u1", poll, cancel, onPaid, onFailed, intervalMs: 2500, timeoutMs: 300_000 }), ); await act(async () => { await vi.advanceTimersByTimeAsync(2500); }); expect(poll).toHaveBeenCalledWith("u1"); expect(onPaid).toHaveBeenCalledTimes(1); expect(cancel).not.toHaveBeenCalled(); expect(onFailed).not.toHaveBeenCalled(); // Stopped — no further polling after a terminal state. await act(async () => { await vi.advanceTimersByTimeAsync(10_000); }); expect(poll).toHaveBeenCalledTimes(1); }); it("stops on FAILED (calls onFailed with the state)", async () => { const poll = vi.fn().mockResolvedValue({ status: "FAILED" }); const onFailed = vi.fn(); renderHook(() => useSplitPoll({ uuid: "u1", poll, cancel: vi.fn(), onPaid: vi.fn(), onFailed, intervalMs: 2500 }), ); await act(async () => { await vi.advanceTimersByTimeAsync(2500); }); expect(onFailed).toHaveBeenCalledWith("FAILED"); }); it("cancels and reports EXPIRED on timeout", async () => { const poll = vi.fn().mockResolvedValue({ status: "PENDING" }); const cancel = vi.fn().mockResolvedValue(true); const onFailed = vi.fn(); renderHook(() => useSplitPoll({ uuid: "u1", poll, cancel, onPaid: vi.fn(), onFailed, intervalMs: 2500, timeoutMs: 10_000 }), ); await act(async () => { await vi.advanceTimersByTimeAsync(10_000); }); expect(cancel).toHaveBeenCalledWith("u1"); expect(onFailed).toHaveBeenCalledWith("EXPIRED"); }); it("stops polling on unmount", async () => { const poll = vi.fn().mockResolvedValue({ status: "PENDING" }); const { unmount } = renderHook(() => useSplitPoll({ uuid: "u1", poll, cancel: vi.fn(), onPaid: vi.fn(), onFailed: vi.fn(), intervalMs: 2500 }), ); await act(async () => { await vi.advanceTimersByTimeAsync(2500); }); const before = poll.mock.calls.length; unmount(); await act(async () => { await vi.advanceTimersByTimeAsync(10_000); }); expect(poll.mock.calls.length).toBe(before); }); });