|
| 1 | +import { renderHook } from '@testing-library/react-hooks' |
| 2 | +import { useMedia } from '..' |
| 3 | + |
| 4 | +describe('useMedia hook', () => { |
| 5 | + it('should return the result of a query with a string', () => { |
| 6 | + const { result } = renderHook(() => |
| 7 | + useMedia('screen and (min-width: 1000px)'), |
| 8 | + ) |
| 9 | + |
| 10 | + expect(result.current).toBe(false) |
| 11 | + }) |
| 12 | + |
| 13 | + it('should call onChange', () => { |
| 14 | + const mockAddEventListener = (_event: string, callback: () => void) => |
| 15 | + callback() |
| 16 | + |
| 17 | + Object.defineProperty(window, 'matchMedia', { |
| 18 | + value: jest.fn().mockImplementation((query: string) => ({ |
| 19 | + addEventListener: mockAddEventListener, |
| 20 | + addListener: jest.fn(), |
| 21 | + dispatchEvent: jest.fn(), |
| 22 | + matches: false, |
| 23 | + media: query, |
| 24 | + onchange: null, |
| 25 | + removeEventListener: jest.fn(), |
| 26 | + removeListener: jest.fn(), |
| 27 | + })), |
| 28 | + writable: true, |
| 29 | + }) |
| 30 | + |
| 31 | + const { result } = renderHook(() => |
| 32 | + useMedia('screen and (min-width: 1000px)'), |
| 33 | + ) |
| 34 | + |
| 35 | + expect(result.current).toBe(false) |
| 36 | + }) |
| 37 | + |
| 38 | + it('should not call onChange when unmounted', () => { |
| 39 | + let callback: () => void |
| 40 | + |
| 41 | + const mockAddEventListener = (_event: string, callbackFn: () => void) => { |
| 42 | + callback = callbackFn |
| 43 | + } |
| 44 | + |
| 45 | + Object.defineProperty(window, 'matchMedia', { |
| 46 | + value: jest.fn().mockImplementation((query: string) => ({ |
| 47 | + addEventListener: mockAddEventListener, |
| 48 | + addListener: jest.fn(), |
| 49 | + dispatchEvent: jest.fn(), |
| 50 | + matches: false, |
| 51 | + media: query, |
| 52 | + onchange: null, |
| 53 | + removeEventListener: jest.fn(), |
| 54 | + removeListener: jest.fn(), |
| 55 | + })), |
| 56 | + writable: true, |
| 57 | + }) |
| 58 | + |
| 59 | + const { result, unmount } = renderHook(() => |
| 60 | + useMedia('screen and (min-width: 1000px)'), |
| 61 | + ) |
| 62 | + |
| 63 | + unmount() |
| 64 | + // @ts-expect-error variable is assigned inside mockAddEventListener |
| 65 | + callback() |
| 66 | + |
| 67 | + expect(result.current).toBe(false) |
| 68 | + }) |
| 69 | +}) |
0 commit comments