Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/wojtekmaj/react-hooks. A collection of React Hooks.
hooks react react-hooks
Something went wrong. Try again.
1.9 kB · 62 lines
TypeScript
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import { afterEach, describe, expect, it, vi } from 'vitest';import { renderHook } from 'vitest-browser-react';import { act } from 'react';
import useWindowSize from './useWindowSize.js';
const itIfWindowDefined = it.runIf(typeof window !== 'undefined');const itIfWindowUndefined = it.runIf(typeof window === 'undefined');
describe('useWindowSize()', () => { afterEach(() => { vi.restoreAllMocks(); });
itIfWindowDefined('should return the window size initially', async () => { const { result } = await renderHook(() => useWindowSize());
expect(result.current).toEqual({ width: window.innerWidth, height: window.innerHeight, }); });
itIfWindowDefined('should update when the window is resized', async () => { let width = 1024; let height = 768;
vi.spyOn(window, 'innerWidth', 'get').mockImplementation(() => width); vi.spyOn(window, 'innerHeight', 'get').mockImplementation(() => height);
const { result } = await renderHook(() => useWindowSize());
expect(result.current).toEqual({ width: 1024, height: 768 });
act(() => { width = 1440; height = 900; window.dispatchEvent(new Event('resize')); });
expect(result.current).toEqual({ width: 1440, height: 900 }); });
itIfWindowDefined('should remove the resize listener on unmount', async () => { const removeEventListener = vi.spyOn(window, 'removeEventListener');
const { unmount } = await renderHook(() => useWindowSize());
expect(removeEventListener).not.toHaveBeenCalled();
await unmount();
expect(removeEventListener).toHaveBeenCalledTimes(1); expect(removeEventListener).toHaveBeenCalledWith('resize', expect.any(Function)); });
itIfWindowUndefined('should return null', async () => { const { result } = await renderHook(() => useWindowSize());
expect(result.current).toBe(null); });});