|
| 1 | +import { act, renderHook } from '@testing-library/react'; |
| 2 | + |
| 3 | +import { createTrigger, renderHookServer } from '@/tests'; |
| 4 | + |
| 5 | +import { useMediaQuery } from './useMediaQuery'; |
| 6 | + |
| 7 | +const trigger = createTrigger<string, () => void>(); |
| 8 | +const mockMatchMedia = { |
| 9 | + matches: false, |
| 10 | + media: '(max-width: 768px)', |
| 11 | + onchange: null, |
| 12 | + addListener: vi.fn(), |
| 13 | + removeListener: vi.fn(), |
| 14 | + addEventListener: (type: string, callback: () => void) => { |
| 15 | + trigger.add(type, callback); |
| 16 | + }, |
| 17 | + removeEventListener: (type: string, callback: () => void) => { |
| 18 | + if (trigger.get(type) === callback) { |
| 19 | + trigger.delete(type); |
| 20 | + } |
| 21 | + }, |
| 22 | + dispatchEvent: vi.fn() |
| 23 | +}; |
| 24 | + |
| 25 | +beforeEach(() => { |
| 26 | + Object.defineProperty(window, 'matchMedia', { |
| 27 | + writable: true, |
| 28 | + value: (query: string) => { |
| 29 | + mockMatchMedia.media = query; |
| 30 | + return mockMatchMedia; |
| 31 | + } |
| 32 | + }); |
| 33 | +}); |
| 34 | + |
| 35 | +afterEach(() => { |
| 36 | + vi.restoreAllMocks(); |
| 37 | +}); |
| 38 | + |
| 39 | +it('Should use media query"', () => { |
| 40 | + const { result } = renderHook(() => useMediaQuery('(max-width: 768px)')); |
| 41 | + |
| 42 | + expect(result.current).toBe(false); |
| 43 | +}); |
| 44 | + |
| 45 | +it('Should use media query on server', () => { |
| 46 | + const { result } = renderHookServer(() => useMediaQuery('(max-width: 768px)')); |
| 47 | + |
| 48 | + expect(result.current).toBe(false); |
| 49 | +}); |
| 50 | + |
| 51 | +it('Should return true if media query matches', () => { |
| 52 | + mockMatchMedia.matches = true; |
| 53 | + |
| 54 | + const { result } = renderHook(() => useMediaQuery('(max-width: 768px)')); |
| 55 | + |
| 56 | + expect(result.current).toEqual(true); |
| 57 | +}); |
| 58 | + |
| 59 | +it('returns false if media query does not match after change', async () => { |
| 60 | + const { result } = renderHook(() => useMediaQuery('(max-width: 768px)')); |
| 61 | + |
| 62 | + expect(result.current).toEqual(true); |
| 63 | + |
| 64 | + mockMatchMedia.matches = false; |
| 65 | + act(() => trigger.callback('change')); |
| 66 | + |
| 67 | + expect(result.current).toEqual(false); |
| 68 | +}); |
0 commit comments