/
testez.tsx
78 lines (66 loc) 路 2.09 KB
/
testez.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
_G.__ROACT_17_MOCK_SCHEDULER__ = true;
import React, { useRef } from "@rbxts/react";
import { act, createLegacyRoot } from "@rbxts/react-roblox";
export interface RenderHookResult<Result, Props> {
/**
* Triggers a re-render. The props will be passed to your renderHook callback.
*/
rerender: (props?: Props) => void;
/**
* A stable reference to the latest value returned by your renderHook callback.
*/
result: {
/**
* The value returned by your renderHook callback.
*/
current: Result;
};
/**
* Unmounts the test component. This is useful for when you need to test any
* cleanup your useEffects have.
*/
unmount: () => void;
}
export interface RenderHookOptions<Props> {
/**
* The container to render into. Defaults to nil, which means the component
* will not be mounted to a Roblox instance.
*/
container?: Instance;
/**
* The argument passed to the renderHook callback. Can be useful if you plan
* to use the rerender utility to change the values passed to your hook.
*/
initialProps?: Props;
}
/**
* Allows you to render a hook within a test React component without having to
* create that component yourself.
* @see https://github.com/testing-library/react-testing-library
*/
export function renderHook<Result, Props>(
render: (initialProps: Props) => Result,
options: RenderHookOptions<Props> = {},
): RenderHookResult<Result, Props> {
const result = { current: undefined as Result };
function TestComponent({ initialProps }: { initialProps?: Props }) {
const previousProps = useRef(initialProps);
const pendingResult = render(initialProps ?? previousProps.current ?? ({} as Props));
previousProps.current = initialProps;
result.current = pendingResult;
return undefined!;
}
const root = createLegacyRoot(options.container || new Instance("Folder"));
act(() => {
root.render(<TestComponent initialProps={options.initialProps} />);
});
const rerender = (props?: Props) => {
act(() => {
root.render(<TestComponent initialProps={props} />);
});
};
const unmount = () => {
act(() => root.unmount());
};
return { rerender, result, unmount };
}