usePrefersColorScheme.spec.ts 2.45 KB
Newer Older
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { createElement, FunctionComponent, StrictMode } from 'react';
import { render } from 'react-dom';
import { act } from 'react-dom/test-utils';

import { usePrefersColorScheme } from '.';
import matchMediaMock from './__mocks__/matchMedia';

describe('usePrefersColorScheme hook', () => {
  let container: HTMLDivElement;

  beforeEach(() => {
    container = document.createElement('div');
    document.body.appendChild(container);
  });

  afterEach(() => {
    container.remove();
    container = null;
  });

  it('should return false on the initial call', () => {
    let matches: boolean;

    const TestComponent: FunctionComponent = () => {
      matches = usePrefersColorScheme();
      return null;
    };

    act(() => {
      render(
        createElement(StrictMode, {}, createElement(TestComponent)),
        container
      );
    });

    expect(matches).toBe(false);
  });

  it('should return true with matchMedia mocked and anything set', () => {
    window.matchMedia = jest.fn((media) =>
      matchMediaMock(media, '(prefers-color-scheme: light)')
    );

    let matches: boolean;
    const TestComponent: FunctionComponent = () => {
      matches = usePrefersColorScheme();
      return null;
    };

    act(() => {
      render(
        createElement(StrictMode, {}, createElement(TestComponent)),
        document.createElement('div')
      );
    });

    expect(matches).toBe(true);
  });

  it('should return true with matchMedia mocked and light scheme set', () => {
    window.matchMedia = jest.fn((media) =>
      matchMediaMock(media, '(prefers-color-scheme: light)')
    );

    let matches: boolean;
    const TestComponent: FunctionComponent = () => {
      matches = usePrefersColorScheme('light');
      return null;
    };

    act(() => {
      render(
        createElement(StrictMode, {}, createElement(TestComponent)),
        document.createElement('div')
      );
    });

    expect(matches).toBe(true);
  });

  it('should return true with matchMedia mocked and dark scheme set', () => {
    window.matchMedia = jest.fn((media) =>
      matchMediaMock(media, '(prefers-color-scheme: dark)')
    );

    let matches: boolean;
    const TestComponent: FunctionComponent = () => {
      matches = usePrefersColorScheme('dark');
      return null;
    };

    act(() => {
      render(
        createElement(StrictMode, {}, createElement(TestComponent)),
        document.createElement('div')
      );
    });

    expect(matches).toBe(true);
  });
});