import { afterEach, describe, expect, it, vi } from 'vitest' import { act, render, screen } from '@testing-library/react' import { useSectionInView } from './useSectionInView' afterEach(() => vi.unstubAllGlobals()) /** An IntersectionObserver the test drives by hand. */ function fakeObserver() { const made: { fire: (ids: [string, boolean][]) => void; observed: string[] }[] = [] class Fake { observed: string[] = [] constructor(cb: IntersectionObserverCallback) { const fire = (ids: [string, boolean][]) => cb( ids.map(([id, on]) => ({ target: document.getElementById(id)!, isIntersecting: on }) as unknown as IntersectionObserverEntry), this as unknown as IntersectionObserver, ) made.push({ observed: this.observed, fire }) } observe(el: Element) { this.observed.push(el.id) } disconnect() {} } vi.stubGlobal('IntersectionObserver', Fake) return made } function Page({ ids }: { ids: string[] }) { const here = useSectionInView(ids) return ( <> {ids.map((id) =>
)} > ) } describe('useSectionInView', () => { it('observes the sections by id and answers the topmost one on screen', () => { const made = fakeObserver() render(