-
Notifications
You must be signed in to change notification settings - Fork 273
/
Copy pathrender-hook.test.tsx
106 lines (82 loc) · 2.67 KB
/
render-hook.test.tsx
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
99
100
101
102
103
104
105
106
import type { ReactNode } from 'react';
import React from 'react';
import TestRenderer from 'react-test-renderer';
import { renderHook } from '../pure';
test('gives committed result', () => {
const { result } = renderHook(() => {
const [state, setState] = React.useState(1);
React.useEffect(() => {
setState(2);
}, []);
return [state, setState];
});
expect(result.current).toEqual([2, expect.any(Function)]);
});
test('allows rerendering', () => {
const { result, rerender } = renderHook(
(props: { branch: 'left' | 'right' }) => {
const [left, setLeft] = React.useState('left');
const [right, setRight] = React.useState('right');
switch (props.branch) {
case 'left':
return [left, setLeft];
case 'right':
return [right, setRight];
default:
throw new Error('No Props passed. This is a bug in the implementation');
}
},
{ initialProps: { branch: 'left' } },
);
expect(result.current).toEqual(['left', expect.any(Function)]);
rerender({ branch: 'right' });
expect(result.current).toEqual(['right', expect.any(Function)]);
});
test('allows wrapper components', () => {
const Context = React.createContext('default');
function Wrapper({ children }: { children: ReactNode }) {
return <Context.Provider value="provided">{children}</Context.Provider>;
}
const { result } = renderHook(
() => {
return React.useContext(Context);
},
{
wrapper: Wrapper,
},
);
expect(result.current).toEqual('provided');
});
const useMyHook = (param: number | undefined) => {
return param;
};
test('props type is inferred correctly when initial props is defined', () => {
const { result, rerender } = renderHook((num: number | undefined) => useMyHook(num), {
initialProps: 5,
});
expect(result.current).toBe(5);
rerender(6);
expect(result.current).toBe(6);
});
test('props type is inferred correctly when initial props is explicitly undefined', () => {
const { result, rerender } = renderHook((num: number | undefined) => useMyHook(num), {
initialProps: undefined,
});
expect(result.current).toBeUndefined();
rerender(6);
expect(result.current).toBe(6);
});
/**
* This test makes sure that calling renderHook does
* not try to detect host component names in any form.
* But since there are numerous methods that could trigger that
* we check the count of renders using React Test Renderers.
*/
test('does render only once', () => {
jest.spyOn(TestRenderer, 'create');
renderHook(() => {
const [state, setState] = React.useState(1);
return [state, setState];
});
expect(TestRenderer.create).toHaveBeenCalledTimes(1);
});