import { render, act } from "@testing-library/react"; import { useRef } from "react"; import { useAdViewability, VIEWABLE_MS } from "./useAdViewability"; let observerCallback; beforeEach(() => { jest.useFakeTimers(); observerCallback = null; global.IntersectionObserver = jest.fn(function IntersectionObserver(cb) { observerCallback = cb; this.observe = jest.fn(); this.disconnect = jest.fn(); }); }); afterEach(() => { jest.useRealTimers(); }); function Banner({ onViewable }) { const ref = useRef(null); useAdViewability(ref, onViewable); return
; } const intersect = (ratio) => act(() => { observerCallback([{ isIntersecting: ratio > 0, intersectionRatio: ratio }]); }); describe("useAdViewability", () => { it("засчитывает показ, когда ≥ 50% видно ≥ 1 секунды", () => { const onViewable = jest.fn(); render(); intersect(0.6); act(() => { jest.advanceTimersByTime(VIEWABLE_MS - 1); }); expect(onViewable).not.toHaveBeenCalled(); act(() => { jest.advanceTimersByTime(1); }); expect(onViewable).toHaveBeenCalledTimes(1); }); it("меньше 50% или ушёл с экрана раньше секунды — не показ", () => { const onViewable = jest.fn(); render(); intersect(0.3); act(() => { jest.advanceTimersByTime(5000); }); intersect(0.8); act(() => { jest.advanceTimersByTime(500); }); intersect(0); act(() => { jest.advanceTimersByTime(5000); }); expect(onViewable).not.toHaveBeenCalled(); }); it("показ засчитывается один раз", () => { const onViewable = jest.fn(); render(); intersect(1); act(() => { jest.advanceTimersByTime(VIEWABLE_MS); }); intersect(0); intersect(1); act(() => { jest.advanceTimersByTime(VIEWABLE_MS * 3); }); expect(onViewable).toHaveBeenCalledTimes(1); }); });