简体   繁体   English

使用 Jest 对 React/Redux 组件进行单元测试

[英]Unit testing using Jest for React/Redux Component

I am testing my connected component using Jest.我正在使用 Jest 测试我的连接组件。 This is how the component looks:这是组件的外观:

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)

I am not sure how to test 'onButtonClick' since it dispatches an action.我不确定如何测试“onButtonClick”,因为它会调度一个动作。 How to I expect dispatch to have been called with correct parameters using jest.我如何期望使用 jest 以正确的参数调用调度。

What you can do is export your component in addition to the default export.除了默认导出之外,您还可以做的是导出您的组件。 So change it to:所以改成:

export class MyComponent extends Component

In your test, you can now import your actual component instead of the connected component.在您的测试中,您现在可以导入您的实际组件而不是连接的组件。 As you have dispatch as a prop of your component, you can supply a mock function or a spy (using something like jasmine or sinon) for dispatch in your test, and you can test if that gets called with the correct parameters.由于您将dispatch作为组件的 prop,您可以在测试中提供模拟函数或间谍(使用类似 jasmine 或 sinon 之类的东西)用于dispatch ,并且您可以测试是否使用正确的参数调用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM