使用Jest for React / Redux Component进行单元测试

时间:2016-10-05 12:56:06

标签: reactjs redux jestjs enzyme

我正在使用Jest测试我的连接组件。 这就是组件的外观:

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

class MyComponent extends Component {
  constructor(){
    super();
    this.onButtonClick = this.onButtonClick.bind(this);
  }

  onButtonClick(id) {
    dispatch(actions.onButtonClick(id));
  }

  render() {
    return (
      <div onClick={this.onButtonClick} />
    )
  }
}

function mapStateToProps(state) {
  something: state.something
}

MyComponent.propTypes = {
  dispatch: PropTypes.func.isRequired
}

export default connect(mapStateToProps)(MyComponent)

我不确定如何测试onButtonClick&#39;因为它发出了一个动作。如何使用jest使用正确的参数调用dispatch。

1 个答案:

答案 0 :(得分:2)

除默认导出外,您还可以导出组件。所以改成它:

export class MyComponent extends Component

在测试中,您现在可以导入实际组件而不是连接组件。由于你有dispatch作为组件的支柱,你可以在测试中为dispatch提供模拟函数或间谍(使用像jasmine或sinon这样的东西),你可以测试是否会调用它用正确的参数。

在此处查看有关redux测试的更多信息: http://redux.js.org/docs/recipes/WritingTests.html

相关问题