-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathuseRafState.test.ts
83 lines (64 loc) · 1.95 KB
/
useRafState.test.ts
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
import { act, renderHook } from '@testing-library/react-hooks';
import { replaceRaf } from 'raf-stub';
import useRafState from '../src/useRafState';
interface RequestAnimationFrame {
reset(): void;
step(): void;
}
declare var requestAnimationFrame: RequestAnimationFrame;
replaceRaf();
beforeEach(() => {
requestAnimationFrame.reset();
});
afterEach(() => {
requestAnimationFrame.reset();
});
describe('useRafState', () => {
it('should be defined', () => {
expect(useRafState).toBeDefined();
});
it('should only update state after requestAnimationFrame when providing an object', () => {
const { result } = renderHook(() => useRafState(0));
act(() => {
result.current[1](1);
});
expect(result.current[0]).toBe(0);
act(() => {
requestAnimationFrame.step();
});
expect(result.current[0]).toBe(1);
act(() => {
result.current[1](2);
requestAnimationFrame.step();
});
expect(result.current[0]).toBe(2);
act(() => {
result.current[1]((prevState) => prevState * 2);
requestAnimationFrame.step();
});
expect(result.current[0]).toBe(4);
});
it('should only update state after requestAnimationFrame when providing a function', () => {
const { result } = renderHook(() => useRafState(0));
act(() => {
result.current[1]((prevState) => prevState + 1);
});
expect(result.current[0]).toBe(0);
act(() => {
requestAnimationFrame.step();
});
expect(result.current[0]).toBe(1);
act(() => {
result.current[1]((prevState) => prevState * 3);
requestAnimationFrame.step();
});
expect(result.current[0]).toBe(3);
});
it('should cancel update state on unmount', () => {
const { unmount } = renderHook(() => useRafState(0));
const spyRafCancel = jest.spyOn(global, 'cancelAnimationFrame' as any);
expect(spyRafCancel).not.toHaveBeenCalled();
unmount();
expect(spyRafCancel).toHaveBeenCalledTimes(1);
});
});