-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathuseMediaQuery.test.js
More file actions
60 lines (50 loc) · 1.71 KB
/
useMediaQuery.test.js
File metadata and controls
60 lines (50 loc) · 1.71 KB
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
import { act, renderHook } from '@testing-library/react';
import { renderToString } from 'react-dom/server';
import { useMediaQuery } from './index.js';
describe('useMediaQuery', () => {
describe('renderHook', () => {
let matches = false;
const listeners = new Set();
beforeAll(() => {
vi.spyOn(window, 'matchMedia').mockImplementation((query) => ({
get matches() {
return matches;
},
media: query,
addEventListener: (event, cb) => listeners.add(cb),
removeEventListener: (event, cb) => listeners.delete(cb),
}));
});
beforeEach(() => {
matches = false;
listeners.clear();
});
afterAll(() => {
window.matchMedia.mockRestore();
});
it('should return true if the media query matches', () => {
matches = true;
const { result } = renderHook(() => useMediaQuery('(min-width: 600px)'));
expect(result.current).toBe(true);
});
it('should return false if the media query does not match', () => {
const { result } = renderHook(() => useMediaQuery('(min-width: 1200px)'));
expect(result.current).toBe(false);
});
it('should update when the media query changes', () => {
const { result } = renderHook(() => useMediaQuery('(min-width: 800px)'));
expect(result.current).toBe(false);
act(() => {
matches = true;
listeners.forEach((cb) => cb());
});
expect(result.current).toBe(true);
});
});
describe('SSR', () => {
it('should not throw during SSR and return false', () => {
const TestComponent = () => String(useMediaQuery('(min-width: 600px)'));
expect(renderToString(<TestComponent />)).toBe('false');
});
});
});