reactjs - 如何使用 Jest 和 enzyme 来模拟导入的 React 高阶组件?

标签 reactjs jestjs enzyme higher-order-components recompose

我正在为一个项目编写一个模块,该项目是一个 HOC,它用多个 HOC 包装了一个应用程序(使用 recompose compose 函数)。我试图测试高阶组件是否确实包装了我的应用程序。

包含 HOC 的示例节点包

//withHOC.js
const withHOC = props => WrappedComponent => moreProps => {
    class HOC extends Component {
        //logic
        render () {
            return <WrappedComponent {...moreProps} />
        }
    }
}
export default withHOC

我的 HOC 使用上面的命名空间 HOC 包装传递的组件

//withWrapper.js
import withHOC from '@HOC/withHOC'
import { compose } from 'recompose'
...etc
const withWrapper = props => WrappedComponent => {
    const innerWrapper => moreProps => (
        <WrappedComponent {...moreProps} />
    );

    const enhance = compose(
        withHOC,
        withHOC1,
        withHOC2,
    );
    return enhance(innerWrapper);
}
export default withWrapper;

测试 withWrapper.js

//withWrapper.test.js
jest.mock('@HOC/withHOC', () => ({
   withWrapper: (Component) => <div id="test"><Component /></div>
}));
import withWrapper from '@HOC/withHOC' 

const TestApp = () => <div>I am a test element</div>
const EnhancedApp = withWrapper(TestApp)
const wrapper = mount(<EnhancedApp />)
describe('test', () => {
    it('withHOC should wrap the app', () => {
        expect(wrapper.find('#test').length).toEqual(1)
    }
}

我正在尝试单独测试我的应用程序,并尝试模拟每个 HOC 以返回一个虚拟包装器。 这就是我目前正在进行的测试,并且在 withWrapper.js 的 compose 部分中收到“TypeError:不是函数”。我也尝试过其他模拟方法,但不断出错,但仍然没有任何进展。

我将如何模拟导入的 HOC?

最佳答案

这是我的通用 HOC 模拟。我希望这就是您正在寻找的内容。

jest.mock("@HOC", () => {
  return {
    withHOC: () => {
      return (Component) => {
        return (props) => {
          return <Component newProp={jest.fn} {...props} />;
        };
      };
    },
  };
});

关于reactjs - 如何使用 Jest 和 enzyme 来模拟导入的 React 高阶组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50897377/

相关文章:

javascript - react + useState() + previousState

reactjs - 如何实现 React Bootstrap 单选按钮

javascript - 关于 React js enzyme 中的状态

reactjs - 如何为一个组件文件运行 Jest 覆盖

node.js - 由于拆卸不当导致 Jest 测试泄漏

javascript - 在 React 组件内的 div 上模拟 ('scroll' )返回 `AssertionError: expected false to be true`

javascript - 如何在react redux中存储多层对象?

javascript - 一个组件中的表单被其他组件提交

javascript - react /Jest/ enzyme : How to test adding text to input and checking for that text?

reactjs - 用 enzyme 测试链接