-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtest-utils.tsx
60 lines (52 loc) · 1.33 KB
/
test-utils.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
import type { ReactNode } from 'react';
import { hydrateRoot } from 'react-dom/client';
import { renderToString } from 'react-dom/server';
import { act } from 'react-dom/test-utils';
// biome-ignore lint/suspicious/noExplicitAny: Too complex to type
export const renderHookServer = <Hook extends () => any>(
useHook: Hook,
{
wrapper: Wrapper,
}: {
wrapper?: ({ children }: { children: ReactNode }) => React.ReactElement;
} = {},
): {
result: { current: ReturnType<Hook> | undefined };
hydrate: () => void;
} => {
// Store hook return values
const results: ReturnType<Hook>[] = [];
const result = {
get current() {
return results.slice(-1)[0];
},
};
const setValue = (value: ReturnType<Hook>) => {
results.push(value);
};
const Component = ({ useHook }: { useHook: Hook }) => {
setValue(useHook());
return null;
};
const component = Wrapper ? (
<Wrapper>
<Component useHook={useHook} />
</Wrapper>
) : (
<Component useHook={useHook} />
);
// Render hook on server
const serverOutput = renderToString(component);
// Render hook on client
const hydrate = () => {
const root = document.createElement('div');
root.innerHTML = serverOutput;
act(() => {
hydrateRoot(root, component);
});
};
return {
result,
hydrate: hydrate,
};
};