forked from streamich/react-use
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useThrottle.test.ts
75 lines (65 loc) · 2.21 KB
/
useThrottle.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
import { renderHook } from '@testing-library/react-hooks';
import useThrottle from '../src/useThrottle';
describe('useThrottle', () => {
beforeAll(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.clearAllTimers();
});
afterAll(() => {
jest.useRealTimers();
});
it('should be defined', () => {
expect(useThrottle).toBeDefined();
});
it('should have a value to be returned', () => {
const { result } = renderHook(() => useThrottle(0, 100));
expect(result.current).toBe(0);
});
it('should has same value if time is advanced less than the given time', () => {
const { result, rerender } = renderHook((props) => useThrottle(props, 100), {
initialProps: 0,
});
expect(result.current).toBe(0);
rerender(1);
jest.advanceTimersByTime(50);
expect(result.current).toBe(0);
});
it('should update the value after the given time when prop change', (done) => {
const hook = renderHook((props) => useThrottle(props, 100), { initialProps: 0 });
expect(hook.result.current).toBe(0);
hook.rerender(1);
expect(hook.result.current).toBe(0);
hook.waitForNextUpdate().then(() => {
expect(hook.result.current).toBe(1);
done();
});
jest.advanceTimersByTime(100);
});
it('should use the default ms value when missing', (done) => {
const hook = renderHook((props) => useThrottle(props), { initialProps: 0 });
expect(hook.result.current).toBe(0);
hook.rerender(1);
hook.waitForNextUpdate().then(() => {
expect(hook.result.current).toBe(1);
done();
});
jest.advanceTimersByTime(200);
});
it('should not update the value after the given time', () => {
const hook = renderHook((props) => useThrottle(props, 100), { initialProps: 0 });
expect(hook.result.current).toBe(0);
jest.advanceTimersByTime(100);
expect(hook.result.current).toBe(0);
});
it('should cancel timeout on unmount', () => {
const hook = renderHook((props) => useThrottle(props, 100), { initialProps: 0 });
expect(hook.result.current).toBe(0);
hook.rerender(1);
hook.unmount();
expect(jest.getTimerCount()).toBe(0);
jest.advanceTimersByTime(100);
expect(hook.result.current).toBe(0);
});
});