-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathuseThrottleFn.test.ts
98 lines (77 loc) Β· 2.73 KB
/
useThrottleFn.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { renderHook, RenderHookResult } from '@testing-library/react-hooks';
import { useThrottleFn } from '../src';
describe('useThrottleFn', () => {
beforeAll(() => {
jest.useFakeTimers();
});
afterAll(() => {
jest.useRealTimers();
});
afterEach(() => {
jest.clearAllTimers();
});
it('should be defined', () => {
expect(useThrottleFn).toBeDefined();
});
const getHook = <T>(initialProps: T, ms?: number): [Function, RenderHookResult<T, T>] => {
const mockFn = jest.fn((props) => props);
return [mockFn, renderHook((props) => useThrottleFn(mockFn, ms, [props]), { initialProps })];
};
it('should return the value that the given function return', () => {
const [fn, hook] = getHook(10, 100);
expect(hook.result.current).toBe(10);
expect(fn).toHaveBeenCalledTimes(1);
});
it('should has same value if time is advanced less than the given time', () => {
const [fn, hook] = getHook(10, 100);
expect(hook.result.current).toBe(10);
expect(fn).toHaveBeenCalledTimes(1);
hook.rerender(20);
jest.advanceTimersByTime(50);
expect(hook.result.current).toBe(10);
expect(fn).toHaveBeenCalledTimes(1);
expect(jest.getTimerCount()).toBe(1);
});
it('should update the value after the given time when arguments change', (done) => {
const [fn, hook] = getHook('boo', 100);
expect(hook.result.current).toBe('boo');
expect(fn).toHaveBeenCalledTimes(1);
hook.rerender('foo');
hook.waitForNextUpdate().then(() => {
expect(hook.result.current).toBe('foo');
expect(fn).toHaveBeenCalledTimes(2);
done();
});
jest.advanceTimersByTime(100);
});
it('should use the default ms value when missing', (done) => {
const [fn, hook] = getHook('boo');
expect(hook.result.current).toBe('boo');
expect(fn).toHaveBeenCalledTimes(1);
hook.rerender('foo');
hook.waitForNextUpdate().then(() => {
expect(hook.result.current).toBe('foo');
expect(fn).toHaveBeenCalledTimes(2);
done();
});
jest.advanceTimersByTime(200);
});
it('should not exist timer when arguments did not update after the given time', () => {
const [fn, hook] = getHook('boo', 100);
expect(hook.result.current).toBe('boo');
expect(fn).toHaveBeenCalledTimes(1);
expect(jest.getTimerCount()).toBe(1);
jest.advanceTimersByTime(100);
expect(jest.getTimerCount()).toBe(0);
});
it('should cancel timeout on unmount', () => {
const [fn, hook] = getHook('boo', 100);
expect(hook.result.current).toBe('boo');
expect(fn).toHaveBeenCalledTimes(1);
hook.rerender('foo');
hook.unmount();
expect(jest.getTimerCount()).toBe(0);
jest.advanceTimersByTime(100);
expect(fn).toHaveBeenCalledTimes(1);
});
});