在测试表单提交时,redux表单的酶测试失败

时间:2017-11-03 18:04:26

标签: reactjs react-redux jestjs redux-form enzyme

我有一个使用redux格式的SignUp React组件,而我的onSubmit基本上会调度异步操作。我正在尝试使用Enzyme和Jest测试我的组件,在我的调度中添加一个间谍并检查是否在模拟表单提交时调用了调度。但是,我的测试失败了。

这是我的SignUp redux表单组件:

import React from 'react';
import {reduxForm, Field, focus} from 'redux-form';
import Input from './input';
import {required, nonEmpty, email, isTrimmed, length} from '../validators';
import {registerUser} from '../actions/users';
import {login} from '../actions/auth';
export class SignUpForm extends React.Component {
    onSubmit(values) {
        const {username, password, fname, lname} = values;
        const newUser = {
            username, 
            password, 
            user: {
               firstName: fname, 
               lastName: lname
            }
        };
        return this.props
            .dispatch(registerUser(newUser))
            .then(() => this.props.dispatch(login(username, password)));
    }

    render() {
        let errorMessage;
        if (this.props.error) {
            errorMessage = (
                <div className="message message-error">{this.props.error </div>
            );
        }

        return (
                <form className='signup-form' onSubmit={this.props.handleSubmit(values =>
                this.onSubmit(values)
            )}>

                    {errorMessage}
                    <Field
                    name="fname"
                    type="text"
                    component={Input}
                    label="First Name"
                    validate={[required, nonEmpty]}
                    />
                    <Field
                    name="lname"
                    type="text"
                    component={Input}
                    label="Last Name"
                    validate={[required, nonEmpty]}
                    />
                    <Field
                    name="username"
                    type="email"
                    component={Input}
                    label="Email"
                    validate={[required, nonEmpty, email, isTrimmed]}
                    />
                    <Field
                    name="password"
                    type="password"
                    component={Input}
                    label="Password"
                    validate={[required, nonEmpty, length({min: 10, max: 72})]}
                    />
                    <button
                    type="submit"
                    disabled={this.props.pristine || this.props.submitting}>
                    Sign Up
                    </button>
                </form>                             
        );
    }
}
export default reduxForm({
    form: 'signup',
    onSubmitFail: (errors, dispatch) => 
        dispatch(focus('signup', Object.keys(errors)[0]))
})(SignUpForm);

这是我的测试:

import React from 'react';
import {shallow, mount} from 'enzyme';
import SignUpForm from './signup';
import {registerUser} from '../actions/users';
import { reducer as formReducer } from 'redux-form'
import { createStore, combineReducers, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import thunk from 'redux-thunk';
import {stockReducer} from '../reducers';
describe('<SignUpForm />', () => {
    let store
    let wrapper
    let dispatch
    beforeEach(() => {
        store = createStore(combineReducers({ form: formReducer, stock: stockReducer }),applyMiddleware(thunk))
        dispatch = jest.fn()
        wrapper = mount(
            <Provider store={store}>
                <SignUpForm dispatch={dispatch}/>
            </Provider>
        );
    })

    it('should fire onSubmit callback when form is submitted', (done) => {
        const form = wrapper.find('form');
        form.find('#fname').simulate('change', {target: {value: 'fname'}});
        form.find('#lname').simulate('change', {target: {value: 'lname'}});
        form.find('#username').simulate('change', {target: {value: 'fname@email.com'}});
        form.find('#password').simulate('change', {target: {value: 'password1234'}});
        form.simulate('submit');
        expect(dispatch).toHaveBeenCalled();
    });
});

我的测试失败,出现以下错误: 期待(jest.fn())。toHaveBeenCalled() 预期的模拟函数已被调用。

请帮助我了解出了什么问题。

1 个答案:

答案 0 :(得分:1)

这里的问题是你没有等待你的onSubmit函数返回的承诺测试中的任何地方,所以你的断言在你的诺言结算之前就被执行了。
我建议你正确地重构你的代码,使其“可测试”。您可以查看以下链接,了解如何使用jest测试异步调用:https://facebook.github.io/jest/docs/en/asynchronous.html
我还建议您使用redux-thunk,这将使您的生活更轻松。