-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathuseDocumentVisibility.test.ts
More file actions
92 lines (69 loc) Β· 2.67 KB
/
useDocumentVisibility.test.ts
File metadata and controls
92 lines (69 loc) Β· 2.67 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
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
import { renderHook, act } from '@testing-library/react-hooks';
import useDocumentVisibility from '../src/useDocumentVisibility';
describe('useDocumentVisibility', () => {
const originalVisibilityState = document.visibilityState;
afterEach(() => {
Object.defineProperty(document, 'visibilityState', {
configurable: true,
value: originalVisibilityState,
});
});
it('should be defined', () => {
expect(useDocumentVisibility).toBeDefined();
});
it('should return false initially', () => {
const { result } = renderHook(() => useDocumentVisibility());
expect(result.current).toBe(false);
});
it('should return true initially when initialState is true', () => {
const { result } = renderHook(() => useDocumentVisibility(true));
expect(result.current).toBe(true);
});
it('should return false initially when initialState is false', () => {
const { result } = renderHook(() => useDocumentVisibility(false));
expect(result.current).toBe(false);
});
it('should return true when document becomes visible', () => {
const { result } = renderHook(() => useDocumentVisibility(true));
act(() => {
Object.defineProperty(document, 'visibilityState', {
configurable: true,
value: 'visible',
});
document.dispatchEvent(new Event('visibilitychange'));
});
expect(result.current).toBe(true);
});
it('should return false when document becomes hidden', () => {
const { result } = renderHook(() => useDocumentVisibility());
act(() => {
Object.defineProperty(document, 'visibilityState', {
configurable: true,
value: 'visible',
});
document.dispatchEvent(new Event('visibilitychange'));
});
expect(result.current).toBe(true);
act(() => {
Object.defineProperty(document, 'visibilityState', {
configurable: true,
value: 'hidden',
});
document.dispatchEvent(new Event('visibilitychange'));
});
expect(result.current).toBe(false);
});
it('should add event listener on mount', () => {
const addEventListenerSpy = jest.spyOn(document, 'addEventListener');
renderHook(() => useDocumentVisibility());
expect(addEventListenerSpy).toHaveBeenCalledWith('visibilitychange', expect.any(Function));
addEventListenerSpy.mockRestore();
});
it('should remove event listener on unmount', () => {
const removeEventListenerSpy = jest.spyOn(document, 'removeEventListener');
const { unmount } = renderHook(() => useDocumentVisibility());
unmount();
expect(removeEventListenerSpy).toHaveBeenCalledWith('visibilitychange', expect.any(Function));
removeEventListenerSpy.mockRestore();
});
});