用玩笑嘲笑高阶组件

hal*_*nes 4 javascript reactjs jestjs

我想确保可以通过玩笑来调用HOC组件,但是我似乎jest.mock无法正常工作。我的HOC是这样的:

const withEntity = (
  ...args
) => {
  const wrappedComponent = WrappedComponent => {
    const innerComponent = ({ ...props }) => {    
      return (
        <WrapperComponent
          {...props}
        >
          <WrappedComponent />
        </WrapperComponent>
      );
    };

    innerComponent.propTypes = {
      ...
    };

    return innerComponent;
  };

  wrappedComponent.propTypes = {
    ...
  };

  return wrappedComponent;
};

withEntity.propTypes = {
  ...
};

export default withEntity;
Run Code Online (Sandbox Code Playgroud)

在一个单独的文件中,该withEntity函数的调用方式如下:

export const DoSomething = withEntity(...args)(MyComponent);
Run Code Online (Sandbox Code Playgroud)

然后,在该DoSomething组件的测试文件中,我试图导入该withEntity函数并对其进行模拟,如下所示:

import withEntity from "../../../shared/entity/higher_order_components/withEntity";
jest.mock("../../../shared/entity/higher_order_components/withEntity");
Run Code Online (Sandbox Code Playgroud)

但是,当我实际尝试运行测试时,出现以下错误:

  ? Test suite failed to run

    TypeError: (0 , _withEntity.default)(...) is not a function
Run Code Online (Sandbox Code Playgroud)

不知道该怎么处理该错误,我在这里做错了什么?

And*_*rle 8

模拟您的HOC应该如下所示:

jest.mock('../your/HOC', () => () => 
    Component => props => <Component {...props} /> 
)
Run Code Online (Sandbox Code Playgroud)

它可以理解为:

jest.mock('../your/HOC', () => `
Run Code Online (Sandbox Code Playgroud)

创建一个返回您的HOC函数的模拟,

() => 
Run Code Online (Sandbox Code Playgroud)

返回您的HOC的功能withEntity(...args)

Component => props => <Component {...props} /> 
Run Code Online (Sandbox Code Playgroud)

HOC本身是一个函数,该函数获取组件并返回一个函数,该函数获取道具,并返回一个函数,该函数返回具有其道具的渲染组件。

  • 我能够让它与 ```jest.mock("../../../shared/entity/higher_order_components/withEntity", () =&gt; jest.fn(() =&gt; jest.fn (Component =&gt; props =&gt; &lt;Component {...props} /&gt;)) );```。现在我的(希望)最后一个问题是:如何检查内部模拟函数(即 `jest.fn(Component ...`) 是否也被调用?我已经尝试过 `expect(withEntity()).toHaveBeenCalledTimes(1 );` 但开玩笑说它被调用了 0 次。 (3认同)