单位测试酶中的React-Redux连接组分

时间:2018-04-23 21:48:50

标签: reactjs ecmascript-6 redux mocha enzyme

我有一个带有表单和按钮的连接组件。使用mount对组件进行单元测试时,我得到错误" Actions必须是普通对象。"

这是因为在handleSubmit方法中进行了redux调用,有没有办法模拟发生的调用。

 import React from "react";
    import {Provider} from "react-redux";
    import configureStore from "redux-mock-store";  
    import {Props, InitialState} from "../mock_data/mock.data.jsx";
    const mockStore = configureStore();
    let store = mockStore(InitialState);
    const params = {
    url: "http://localhost:9879"
    };
    let props = {};
  beforeEach(() => {
    // reset props before each test
    props = JSON.parse(JSON.stringify(Props));
    props.actions = {};
   props.email = Props.email;
    props.params = params;
  });
    handleSubmit({ values }) {
        const {url} = this.props;
        const val = values.valcode;
        this.props.actions.getCode(url);
        this.props.makeExternalCall(val);
      }


      return (
              <Form
                initialValues={{ ...personalUser }}
                onSubmit={this.handleSubmit}>
                {
                  ({ form, errors }) => {
                    const isDisabled = errors !== null || this.state.disableReset;

                    return (
                      <div>
                        <button name="btnConfirm" type="submit"
                          className={styles.btnConfirm} disabled={isDisabled}>/>
                        </button>
                      </div>
                    );
                  }
                }
              </Form>
            );

    const mapDispatchToProps = (dispatch) => ({
      actions: bindActionCreators(actions, dispatch),
      makeExternalCall: bindActionCreators(makeExternalCallAction, dispatch)
    });

export default connect(null, mapDispatchToProps)(injectIntl(TestComponent));

测试

it(" - should display the proper label", () => {

    props.error = "This is an error message";
    props.actions.getCode = sinon.stub().returns({
      then: () => {}
    });
    props.makeExternalCall = sinon.stub().returns({
      then: () => {}
    });
    store = mockStore(props);
    const wrapper = mountWithIntl(<Provider store={store}>
        <TestComponent {...props}/>
      </Provider>);
    expect(wrapper).to.not.be.null;
    expect(wrapper.find("button").prop("disabled")).equals(true);
   wrapper.find("TestComponent").get(0).handleSubmit({values:{valcode: "AkPdQ2" }});
  });

是否可以模拟mapDispatchToProps,它会给出错误

PhantomJS 2.1.1 (Mac OS X 0.0.0) <TestComponent Component />  - should display the proper label FAILED
    Actions must be plain objects. Use custom middleware for async actions.

0 个答案:

没有答案