在Jest + Enzyme中测试Connected Container方法

时间:2018-01-20 03:03:13

标签: reactjs unit-testing redux jestjs enzyme

我有一个像这样的连接容器:

import React from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { autobind } from 'core-decorators';

const propTypes = {
  data: PropTypes.object,
  userData: PropTypes.object,
};

class ConnectedContainer extends React.Component {
    @autobind
    doSomethingImportant() {
      ...
    }

  render() {
    ....
  }
}

ConnectedContainer.propTypes = propTypes;

const mapStateToProps = state => ({ data, userData });
const mapDispatchToProps = (dispatch) => {
  return { actions: bindActionCreators(actions, dispatch) };
};
export default connect(mapStateToProps, mapDispatchToProps)(ConnectedContainer);

我想测试doSomethingImportant,所以我有这样的测试:

import React from 'react';
import { shallow } from 'enzyme';
import ConnectedContainer from '.....'';
import configureStore from 'redux-mock-store';

const mockStore = configureStore();
const store = mockStore({ getState: () => null, dispatch: () => null, data: { data from fixture }, userData: { data from fixture } });
const container = (
  <ConnectedContainer
    store={store}
    actions={{}}
  />
);

describe('ConnectedContainer', () => {
  describe('doSomethingImportant', () => {
    it('returns something important', () => {
      const wrapper = shallow(container);
      expect(wrapper.instance().doSomethingImportant()).to.equal( ... some output here );
    });
  });
});

无论我做什么,我都会收到这个错误:

TypeError: wrapper.instance(...). doSomethingImportant is not a function

我的容器发生了什么,我无法访问其实例方法?

2 个答案:

答案 0 :(得分:5)

测试展开的组件

导出ConnectedContainer类本身,而不是包装版本。您想测试代码,而不是connect()函数。

您可以将默认导出保留为包装组件,然后在类定义前面添加单词export

export class ConnectedContainer extends React.Component { // Named export, for testing purposes only
    ...
}

然后在您的测试中,import { ConnectedContainer } from '....' 使用shallow而不是默认导出进行渲染。

命名约定

此外,命名组件ConnectedContainer非常令人困惑!它只有在用connect函数包装后才会连接。因此,当您导出ConnectedContainer时(正如我所建议的那样),您实际上是在导出未连接的组件类。 (它实际上是一个容器吗?这也很模糊。)

人们使用的一个命名约定是定义一个包含connect()返回值的常量,并命名 xxxContainer,如下所示:

export class IconView extends React.Component {  // Exported for testing
  // ... class implementation
}

function mapStateToProps(){...}
function mapDispatchToProps(){...}

const IconViewContainer = connect(mapStateToProps, mapDispatchToProps)(IconView);
export default IconViewContainer;  // Exported for use as a component in other views

答案 1 :(得分:0)

尝试:

const Container = (
  <ConnectedContainer
    store={store}
    actions={{}}
  />
);

注意,唯一的区别是容器中的C大写。问题是React只将类和方法视为组件,如果它们以大写字母开头。那可能是你的问题。