简体   繁体   English

无法测试redux-form

[英]Unable to test redux-form

I'm having difficulty testing react components that are decorated with redux-form. 我在测试用redux形式装饰的组件时遇到困难。 Here are some of the integration tests I'm trying to run. 这是我要运行的一些集成测试。 They are all failing, so it's clear that I haven't set up the tests properly. 它们都失败了,因此很明显我没有正确设置测试。 There appears to be a lot of discussion here and on GitHub on how challenging it can be to conduct unit and integration tests with redux-form. 在这里和在GitHub上似乎有很多讨论,讨论使用redux-form进行单元和集成测试有多艰巨。 Any help would be appreciated. 任何帮助,将不胜感激。

confirmation.js confirmation.js

import React, { Component } from 'react';
import { reduxForm, Field } from 'redux-form';
import { connect } from 'react-redux';
import { sendActivationEmail, resetAuthError } from '../../actions';

export const renderField = ({ input, label, type, meta: { touched, error } }) => (
  <fieldset className="form-group">
    <div className={touched && error ? 'has-danger' : ''}>
      <p>Resend Confirmation Instructions</p>
      <input {...input} placeholder={label} type={type} className="form-control"/>
      {touched && error && <span className="error">{error}</span>}
    </div>
  </fieldset>
)

export class Confirmation extends Component {
  componentWillUnmount() {
    this.props.resetAuthError();
  }

  handleFormSubmit({ email }) {
    this.props.sendActivationEmail({ email });
  }

  renderAlert() {
    if (this.props.errorMessage) {
      return (
        <div className="alert alert-danger">
          <strong>Oops!</strong> {this.props.errorMessage}
        </div>
      )
    }
  }

  render() {
    const { handleSubmit } = this.props;
    return (
      <div>
        {this.renderAlert()}
        <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
          <Field
            label="Email"
            name="email"
            component={renderField}
            type="text"
          />
          <button type="submit" className="btn btn-primary">Resend</button>
        </form>
      </div>
    );
  }
}

 function validate(formProps) {
  const errors = {};

  if (!formProps.email) {
    errors.email = 'Please enter an email';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(formProps.email)) {
    errors.email = 'Please enter a valid email address';
  }

  return errors;
}

function mapStateToProps(state) {
  return { errorMessage: state.auth.error }
}

Confirmation = reduxForm({
  form: 'confirmation',
  validate
})(Confirmation);

Confirmation = connect(mapStateToProps, { sendActivationEmail, resetAuthError 
})(Confirmation);

export default Confirmation;

confirmation_test.js confirmation_test.js

import React from 'react';
import { expect } from 'chai';
import { shallow, mount, unmount } from 'enzyme';
import sinon from 'sinon';

import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reduxThunk from 'redux-thunk';

import reducers from '../../../src/reducers';
import ConfirmationContainer, { ConfirmationComponent, renderField }  from '../../../src/components/auth/confirmation';

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(reducers);

  describe('Container', () => {
    let sendActivationEmail, resetAuthError, props, errorMessage, subject;
    beforeEach(() => {
      sendActivationEmail = sinon.spy();
      resetAuthError = sinon.spy();
      props = {
        sendActivationEmail,
        resetAuthError,
        errorMessage: 'required'
      };

      subject = mount(
        <Provider store={store}>
          <ConfirmationContainer {...props} />
        </Provider>
        )
      });

    it('renders error message', (done) => {
      expect(subject.find('.alert')).to.have.length(1);
      done();
    });

    it('calls sendActivationEmail on submit', (done)=> {
        const form = subject.find('form');
        const input = subject.find('input').first();

        input.simulate('change', { target: { value: 'test@gmail.com' } });
        form.simulate('submit');
        expect(sendActivationEmail.callCount).to.equal(1);
        done();
    });

    it('calls resetAuthError on unmount', (done) => {
        subject.unmount();
        expect(resetAuthError.calledOnce).to.equal(true);
    });
  });

Adding mergeProps as the third argument to the connect() function made my first two tests pass. mergeProps作为第三个参数添加到connect()函数使我的前两个测试通过了。 For the third test, I added done() at the end of the test, which I initially neglected to add. 对于第三个测试,我在测试结束时添加了done() ,而我最初忽略了添加。 Here is the code I added to my container component to make my tests pass: 这是我添加到容器组件以使测试通过的代码:

const mergeProps = (stateProps, dispatchProps, ownProps) =>
    Object.assign({}, stateProps, dispatchProps, ownProps)

Confirmation = connect(mapStateToProps, { sendActivationEmail, resetAuthError 
}, mergeProps)(Confirmation);

Thanks to @tylercollier on this thread for helping me find this solution. 感谢此线程上的@tylercollier帮助我找到此解决方案。

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

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