【发布时间】:2020-04-13 09:49:30
【问题描述】:
以下是 HOC 的代码
const HOC = ({ component: Component }) => {
return () => {
const id = useQuery(query);
return (<div>
{!id ? ( <SomeOtherComponent prop1={'hello'} prop2={'world'} /> ) : ( <Component /> )}
</div>)
}
}
下面是渲染HOC的测试-
const myComponent = () => <div data-testid={'component-testid'}>ABC</div>;
const renderHOC = HOC({component: myComponent})();
const {getByTestId} = render(renderHOC);
expect(getByTestId('component-testid')).toBeInTheDocument();
得到错误- 无效的挂钩调用。必须在 react 功能组件内部调用 React 钩子。
【问题讨论】:
-
现在你的代码中没有钩子。
Component和SomeOtherComponent分别是什么?它们是一样的吗? -
useQuery() 是钩子。这是两个独立的组件。HOC 在 UI 上运行良好,但是我无法编写相同的测试。
-
啊!然后您应该能够通过将
const id = useQuery(query);移出return () => {...}语句来解决此问题。
标签: reactjs react-hooks higher-order-functions react-testing-library