import { act, render, renderHook } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; import { hydrate, renderToString } from '@/test/hydrate'; import usePageLoaded from './usePageLoaded'; const seen: boolean[] = []; function Probe() { const loaded = usePageLoaded(); seen.push(loaded); return

{String(loaded)}

; } describe('usePageLoaded', () => { it('is true when the page had already loaded', () => { const { result } = renderHook(() => usePageLoaded()); expect(result.current).toBe(true); }); it('turns true on the load event', () => { const readyState = vi .spyOn(document, 'readyState', 'get') .mockReturnValue('interactive'); const { result } = renderHook(() => usePageLoaded()); expect(result.current).toBe(false); act(() => { // The browser is 'complete' by the time the load event fires readyState.mockReturnValue('complete'); window.dispatchEvent(new Event('load')); }); expect(result.current).toBe(true); }); it('is false in the server render, even when the page has loaded', () => { expect(renderToString()).toBe('

false

'); }); it('is false in the hydrating render and true right after on a loaded page', () => { seen.length = 0; const { container, errors } = hydrate(); expect(seen[0]).toBe(false); expect(seen.at(-1)).toBe(true); expect(container).toHaveTextContent('true'); expect(errors).toEqual([]); }); it('stays false after hydrating until the load event', () => { const readyState = vi .spyOn(document, 'readyState', 'get') .mockReturnValue('interactive'); const { container, errors } = hydrate(); expect(container).toHaveTextContent('false'); act(() => { readyState.mockReturnValue('complete'); window.dispatchEvent(new Event('load')); }); expect(container).toHaveTextContent('true'); expect(errors).toEqual([]); }); it('is true at once for a component that mounts on a loaded page', () => { seen.length = 0; render(); expect(seen).toEqual([true]); }); });