【问题标题】:Unable to test HOC containing hooks using React testing library无法使用 React 测试库测试包含钩子的 HOC
【发布时间】: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 钩子。

【问题讨论】:

  • 现在你的代码中没有钩子。 ComponentSomeOtherComponent 分别是什么?它们是一样的吗?
  • useQuery() 是钩子。这是两个独立的组件。HOC 在 UI 上运行良好,但是我无法编写相同的测试。
  • 啊!然后您应该能够通过将const id = useQuery(query); 移出return () =&gt; {...} 语句来解决此问题。

标签: reactjs react-hooks higher-order-functions react-testing-library


【解决方案1】:

应该是这样的

const RenderHOC = HOC({component: myComponent});
const { getByTestId } = render(<RenderHOC />);

如果组件包含钩子,则不能将其作为函数调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-29
    • 2021-05-09
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2021-06-07
    • 2021-06-08
    相关资源
    最近更新 更多