-
Notifications
You must be signed in to change notification settings - Fork 3
/
render-hook.tsx
83 lines (72 loc) · 2.12 KB
/
render-hook.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
// source: https://github.com/testing-library/react-testing-library/blob/887d95b84ddbcedb46932bf52fbda4518abb35c8/src/pure.js#L118
import { act, render } from '@testing-library/react';
import React, {
ComponentType,
createRef,
Fragment,
MutableRefObject,
StrictMode,
useEffect,
} from 'react';
interface RenderHookResult<Result, Props> {
rerender: (props: Props) => void;
result: { current: Result };
unmount: () => void;
}
interface RenderHookOptions<Props> {
initialProps: Props;
wrapper?: ComponentType;
strict?: boolean;
}
interface RenderHookResultWithoutProps<Result> {
rerender: () => void;
result: { current: Result };
unmount: () => void;
}
interface RenderHookOptionsWithoutProps {
wrapper?: ComponentType;
strict?: boolean;
}
export function renderHook<Result>(
renderCallback: () => Result,
options?: RenderHookOptionsWithoutProps,
): RenderHookResultWithoutProps<Result>;
export function renderHook<Result, Props>(
renderCallback: (props: Props) => Result,
options: RenderHookOptions<Props>,
): RenderHookResult<Result, Props>;
export function renderHook<Result, Props>(
renderCallback: (props?: Props) => Result,
options: Partial<RenderHookOptions<Props>> = {},
): RenderHookResult<Result, Props> | RenderHookResultWithoutProps<Result> {
const { initialProps, wrapper, strict = true } = options;
const Wrapper = strict ? StrictMode : Fragment;
const result: MutableRefObject<Result> =
createRef() as MutableRefObject<Result>;
function TestComponent({
renderCallbackProps,
}: {
renderCallbackProps?: Props;
}) {
const pendingResult = renderCallback(renderCallbackProps);
useEffect(() => {
result.current = pendingResult;
});
return null;
}
const { rerender: baseRerender, unmount } = render(
<Wrapper>
<TestComponent renderCallbackProps={initialProps} />
</Wrapper>,
{ wrapper },
);
function rerender(rerenderCallbackProps?: Props) {
return baseRerender(
<Wrapper>
<TestComponent renderCallbackProps={rerenderCallbackProps} />
</Wrapper>,
);
}
return { result, rerender, unmount };
}
export { act };