forked from SmartDropLabs/smartdrop-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderHook.tsx
More file actions
50 lines (43 loc) · 1.13 KB
/
Copy pathrenderHook.tsx
File metadata and controls
50 lines (43 loc) · 1.13 KB
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
import {
Fragment,
act,
createElement,
type ComponentType,
type ReactNode,
} from "react";
import { createRoot } from "react-dom/client";
type HookWrapper = ComponentType<{ children: ReactNode }>;
export function renderHook<T>(
callback: () => T,
options?: { wrapper?: HookWrapper }
) {
const result = { current: undefined as T };
const container = document.createElement("div");
document.body.appendChild(container);
const Wrapper = options?.wrapper ?? Fragment;
function HookHarness() {
result.current = callback();
return null;
}
const root = createRoot(container);
// `callback` is a closure — a caller that captures an outer `let` and
// mutates it before calling `rerender()` will see the hook re-invoked
// with the new value, the same way @testing-library/react-hooks works.
function renderOnce() {
act(() => {
root.render(createElement(Wrapper, null, createElement(HookHarness)));
});
}
renderOnce();
return {
result,
rerender: renderOnce,
unmount: () => {
act(() => {
root.unmount();
});
container.remove();
},
};
}
export { act };