用玩笑嘲笑高阶组件

时间:2018-11-07 22:38:35

标签: 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;

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

export const DoSomething = withEntity(...args)(MyComponent);

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

import withEntity from "../../../shared/entity/higher_order_components/withEntity";
jest.mock("../../../shared/entity/higher_order_components/withEntity");

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

  ● Test suite failed to run

    TypeError: (0 , _withEntity.default)(...) is not a function

不确定导致该错误的原因是什么,我在这里做错了什么?

2 个答案:

答案 0 :(得分:3)

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

jest.mock('../your/HOC', () => () => 
    Component => props => <Component {...props} /> 
)

它可以读作:

jest.mock('../your/HOC', () => `

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

() => 

返回您的HOC aka withEntity(...args)的函数,

Component => props => <Component {...props} /> 

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

答案 1 :(得分:1)

就我而言,因为我使用的是打字稿,所以这对我很有效。

jest.mock('components/MyComponent', () => ({
  __esModule: true,
  default({children}: any) {
    return children(() => {});
  },
}));