File size: 1,491 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
44
45
46
47
48
49
50
51
52
import React, { useState } from 'react';

import type { Breakpoint } from '../..';
import { fireEvent, render } from '../../../tests/utils';
import Sider from '../Sider';

const Content = () => {
  const [breakpoint, setBreakpoint] = useState<Breakpoint>('sm');
  const toggleBreakpoint = () => {
    if (breakpoint === 'sm') {
      setBreakpoint('lg');
    } else {
      setBreakpoint('sm');
    }
  };
  return (
    <Sider breakpoint={breakpoint}>
      <button type="button" id="toggle" onClick={toggleBreakpoint}>
        Toggle
      </button>
    </Sider>
  );
};

it('Dynamic breakpoint in Sider component', () => {
  const add = jest.fn();
  const remove = jest.fn();
  const newMatch = jest.spyOn(window, 'matchMedia').mockReturnValue({
    matches: true,
    addEventListener: add,
    removeEventListener: remove,
  } as any);

  const { container } = render(<Content />);

  // Record here since React 18 strict mode will render twice at first mount
  const originCallTimes = newMatch.mock.calls.length;
  expect(originCallTimes <= 2).toBeTruthy();

  // subscribe at first
  expect(add.mock.calls).toHaveLength(originCallTimes);
  expect(remove.mock.calls).toHaveLength(originCallTimes - 1);

  fireEvent.click(container.querySelector('#toggle') as Element);

  expect(newMatch.mock.calls).toHaveLength(originCallTimes + 1);
  expect(add.mock.calls).toHaveLength(originCallTimes + 1);
  expect(remove.mock.calls).toHaveLength(originCallTimes);

  jest.restoreAllMocks();
});