【问题标题】:Enzyme test for redux form fails when testing form submission测试表单提交时,redux 表单的酶测试失败
【发布时间】:2018-11-06 05:41:15
【问题描述】:

我有一个使用 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() 预期的模拟函数已被调用。

请帮助我了解发生了什么问题。

【问题讨论】:

  • 不确定 reduxForm 是如何工作的,但也许您应该将调度从 reduxForm 传递给实际组件 SignUpForm ?只是一个想法

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-01-04
    • 2020-04-09
    • 2014-06-28
    • 2018-09-30
    • 1970-01-01
    • 2018-10-26
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多