Files
co-lite/solvway-admin-portal/app/lib/hooks/usePolling.test.ts
T
ngqileandClaude Opus 5.5 1d5e792e3d feat: whatsapp portal proxy, client service and polling hook
Part of tasks 5.1/5.2 (not ticked): one catch-all proxy at /api/whatsapp (media
served with nosniff and a sandbox CSP), typed client calls, and usePolling that
pauses while the tab is hidden.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-02 11:03:56 +08:00

52 lines
1.8 KiB
TypeScript

// @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();
});
});