用酶和茉莉花测试高阶成分

时间:2018-06-29 16:22:10

标签: reactjs testing redux jasmine enzyme

使用Jasmine和Enzyme进行测试,我一直在尝试测试连接到redux的HOC。以下面的HOC为例:

import React, { Component } from 'react';
import { connect } from 'react-redux';

const WithAreas = (WrappedComponent) => {
  class WithAreasComponent extends Component {
    constructor(props) {
      super(props);    
    }    

    shouldRenderWrappedComponent(userObj) {
      return !!userObj.areas;
    }

    render() {
      const { userObj } = this.props;

      return shouldRenderWrappedComponent(userObj)
        ? <WrappedComponent {...this.props} />
        : null;
    }
  }

  function mapStateToProps(state) {
    const { info } = state;
    const { userObj } = info.userObj;

    return { userObj };
  }

  return connect(mapStateToProps)(WithAreasComponent);
};

export default WithAreas;

假设我要测试此HOC,以便检查是否根据userObj渲染了包装的组件。我考虑过要制作一个模拟组件并将其传递给HOC,但这是行不通的。

Test.js文件:

import React from 'react';
import { shallow } from 'enzyme';
import jasmineEnzyme from 'jasmine-enzyme';

import WithAreas from './';

class MockComponent extends React.Component {
  render() {
    return(
      <div> MOCK </div>
    );
  }
}

function setup(extraProps) {
  const props = {
   info: {
    userObj: {
     id: 'example1'
    }
   },
  };

  Object.assign(props, extraProps);

  const WithAreasInstance = WithAreas(MockComponent);
  const wrapper = shallow(<WithAreasInstance {...props} />);

  return {
    props,
    wrapper
  };
}

fdescribe('<WithAreas />', () => {
  beforeEach(() => {
    jasmineEnzyme();
  });
  it('should render the Mock Component', () => {
    const { wrapper } = setup();
    expect(wrapper.find(MockComponent).exists()).toBe(true);
  });
});

但是它给了我这个错误:

TypeError: (0 , _.WithAreas) is not a function at setup (webpack:///src/user/containers/WithAreas/test.js:20:47 <- src/test_index.js:9:18060087) at UserContext.<anonymous> (webpack:///src/user/containers//WithAreas/test.js:34:24 <- src/test_index.js:9:18060822) 我究竟做错了什么?或您会推荐哪种方法?

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您没有正确导入测试中的HOC。您已将其设置为默认导出,但正在使用命名的导出解构。

在测试文件中尝试一下:

import WithAreas from './';

此外,请不要忘记将存储传递给测试中的组件,否则connect HOC无法按预期工作。

shallow(
  <Provider store={store}>
    <WithAreasInstance ...>
  </Provider>)