forked from siberiacancode/reactuse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderHookServer.tsx
More file actions
52 lines (45 loc) · 1.35 KB
/
renderHookServer.tsx
File metadata and controls
52 lines (45 loc) · 1.35 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
51
52
import type { ReactNode } from 'react';
import { hydrateRoot } from 'react-dom/client';
import { renderToString } from 'react-dom/server';
import { act } from 'react-dom/test-utils';
/**
* @see https://github.com/testing-library/react-testing-library/issues/1120#issuecomment-1516132279
* currently there is no correct way how to test server-side rendered hooks before hydration in rtl
*/
export const renderHookServer = <Hook extends () => any>(
useHook: Hook,
{
wrapper: Wrapper
}: {
wrapper?: ({ children }: { children: ReactNode }) => JSX.Element;
} = {}
): { result: { current: ReturnType<Hook> }; hydrate: () => void } => {
const results: Array<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() as ReturnType<Hook>);
return null;
};
const component = Wrapper ? (
<Wrapper>
<Component useHook={useHook} />
</Wrapper>
) : (
<Component useHook={useHook} />
);
const serverOutput = renderToString(component);
const hydrate = () => {
const root = document.createElement('div');
root.innerHTML = serverOutput;
act(() => hydrateRoot(root, component));
};
return {
result,
hydrate
};
};