File size: 1,639 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { renderHook } from '@testing-library/react-hooks';
import { renderHook as renderHookSSR } from '@testing-library/react-hooks/server';
import { useMedia } from '../src';

const createMockMediaMatcher = (matches: Record<string, boolean>) => (qs: string) => ({
  matches: matches[qs] ?? false,
  addEventListener: () => {},
  removeEventListener: () => {},
});

describe('useMedia', () => {
  beforeEach(() => {
    window.matchMedia = createMockMediaMatcher({
      '(min-width: 500px)': true,
      '(min-width: 1000px)': false,
    }) as any;
  });
  it('should return true if media query matches', () => {
    const { result } = renderHook(() => useMedia('(min-width: 500px)'));
    expect(result.current).toBe(true);
  });
  it('should return false if media query does not match', () => {
    const { result } = renderHook(() => useMedia('(min-width: 1200px)'));
    expect(result.current).toBe(false);
  });
  it('should return default state before hydration', () => {
    const { result } = renderHookSSR(() => useMedia('(min-width: 500px)', false));
    expect(result.current).toBe(false);
  });
  it('should return media query result after hydration', async () => {
    const { result, hydrate } = renderHookSSR(() => useMedia('(min-width: 500px)', false));
    expect(result.current).toBe(false);
    hydrate();
    expect(result.current).toBe(true);
  });
  it('should return media query result after hydration', async () => {
    const { result, hydrate } = renderHookSSR(() => useMedia('(min-width: 1200px)', true));
    expect(result.current).toBe(true);
    hydrate();
    expect(result.current).toBe(false);
  });
});