[英]How to test Component which requires hook using react testing library?
I have built a component which requires a methods and data supplied by custom hook我已经构建了一个组件,它需要自定义钩子提供的方法和数据
const MyComponent = () => {
const { data, methods } = useMyCustomHook({ defaultValues: defaultValues });
return <MyAnotherComponent data={data} label="Some Text" method={methods} />;
}
I am writing test using react testing library to test MyComponent
or to be more specific to test MyAnotherComponent
我正在使用反应测试库编写测试来测试
MyComponent
或更具体地测试MyAnotherComponent
Here is my testing code这是我的测试代码
test("Test MyAnotherComponent Label", () => {
const { data, methods } = useMyCustomHook({ defaultValues: defaultValues });
render(
<MyAnotherComponent
data={data}
label="Some Text"
method={methods}
/>
);
expect(screen.getByLabelText("Some Text")).toBeInTheDocument();
});
My testcase fails with an error saying Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons
我的测试用例失败,错误提示
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons
I have looked up for solutions but some are too simple and some are too complex.我一直在寻找解决方案,但有些太简单了,有些太复杂了。 Thanks in advance
提前致谢
The error is caused by the fact that you are calling the hook inside a function, not inside a React component.该错误是由于您在 function 内调用钩子,而不是在 React 组件内。 Since you only want to test MyAnotherComponent, I don't see why you'd need to call the hook and not mock the
data
and methods
directly to pass them to MyAnotherComponent because what you are currently doing is to re-write MyComponent
.由于您只想测试 MyAnotherComponent,我不明白为什么您需要调用钩子而不是直接模拟
data
和methods
以将它们传递给 MyAnotherComponent,因为您当前正在做的是重新编写MyComponent
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.