// @vitest-environment jsdom import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { renderHook } from "@testing-library/react"; import { act } from "react"; import { usePolling } from "./usePolling"; let hidden = false; beforeEach(() => { vi.useFakeTimers(); hidden = false; Object.defineProperty(document, "hidden", { configurable: true, get: () => hidden }); }); afterEach(() => vi.useRealTimers()); describe("usePolling", () => { it("runs now and then every interval", () => { const fn = vi.fn(); renderHook(() => usePolling(fn, 1000)); expect(fn).toHaveBeenCalledTimes(1); act(() => { vi.advanceTimersByTime(3000); }); expect(fn).toHaveBeenCalledTimes(4); }); it("skips ticks while the tab is hidden and catches up when it shows", () => { const fn = vi.fn(); renderHook(() => usePolling(fn, 1000)); hidden = true; act(() => { vi.advanceTimersByTime(3000); }); expect(fn).toHaveBeenCalledTimes(1); hidden = false; act(() => { document.dispatchEvent(new Event("visibilitychange")); }); expect(fn).toHaveBeenCalledTimes(2); }); it("stops after unmount and runs when the named window event fires", () => { const fn = vi.fn(); const { unmount } = renderHook(() => usePolling(fn, 1000, "whatsapp-unread-changed")); act(() => { window.dispatchEvent(new Event("whatsapp-unread-changed")); }); expect(fn).toHaveBeenCalledTimes(2); unmount(); act(() => { vi.advanceTimersByTime(3000); window.dispatchEvent(new Event("whatsapp-unread-changed")); }); expect(fn).toHaveBeenCalledTimes(2); }); it("does nothing when disabled", () => { const fn = vi.fn(); renderHook(() => usePolling(fn, 1000, undefined, false)); act(() => { vi.advanceTimersByTime(3000); }); expect(fn).not.toHaveBeenCalled(); }); });