【发布时间】:2018-02-06 08:17:08
【问题描述】:
我正在编写一个 Jest 测试来检查当我提交一个使用 redux-form 构建的表单时是否调度了一个动作。我正在存根操作并直接调用提交处理程序handleFormSubmit。我期待dispatch 以我的存根操作作为参数被调用,但断言一直失败。该应用程序确实按预期工作,但我无法弄清楚为什么这个测试失败了。
这是组件(一个简单的登录表单):
import React from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { userSignIn } from "../actions";
import styled from 'styled-components';
import * as formValidators from '../utils/formValidators';
import TextInput from '../components/TextInput';
import Button from '../components/Button';
/*
... styled components code
*/
export class Login extends React.Component {
handleFormSubmit = (credentials) => {
this.props.userSignIn(credentials);
};
render() {
return(
<StyledDiv>
<StyledForm onSubmit={this.props.handleSubmit(this.handleFormSubmit)}>
<fieldset className="form-group">
<Field name="email" component={TextInput} type="text" label="Email"/>
</fieldset>
<fieldset className="form-group">
<Field name="password" component={TextInput} type="password" label="Password"/>
</fieldset>
<Button type="submit" label="Sign In"/>
</StyledForm>
</StyledDiv>
);
}
}
const LoginContainer = reduxForm({
form: 'login',
validate: formValidators.createValidator({
email:formValidators.email,
password:formValidators.required
})
})(Login);
function mapStateToProps(state) {
return {
authenticationError: state.auth.error
}
}
function mapDispatchToProps(dispatch) {
return {
userSignIn: (credentials) => dispatch(userSignIn(credentials))
}
}
const mergeProps = (stateProps, dispatchProps, ownProps) =>
Object.assign({}, stateProps, dispatchProps, ownProps);
export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(LoginContainer);
这是我的 Jest 测试:
import React from 'react';
import ConnectedLogin, {Login} from '../../containers/Login';
import EnzymeToJson from 'enzyme-to-json';
import {shallow, mount} from 'enzyme';
import sinon from 'sinon';
import configureMockStore from "redux-mock-store";
import * as Actions from '../../actions';
describe('Connected Login component', () => {
const mockStore = configureMockStore();
let wrapper;
let store;
beforeEach(() => {
store = mockStore();
wrapper = shallow(<ConnectedLogin store={store} />);
});
test('userSignIn is dispatched', () => {
const storeSpy = sinon.spy(store, 'dispatch');
const credentials = {
email: "foo@bar.com",
password: "foobar"
};
const stub = sinon.stub(Actions, 'userSignIn').callsFake(() => {
return {
type: 'USER_SIGN_IN',
}
});
//need to dive multiple times since this is a component in a redux form in a redux container
wrapper.dive().dive().dive().dive().instance().handleFormSubmit(credentials);
expect(storeSpy.calledWith(stub())).toBe(true)
});
});
【问题讨论】:
-
你确定这有效吗?
this.props.handleSubmit未定义。 -
@moritz-schmitz-v-hülst 是的,我相信这是作为来自 redux-form 包装器的道具传递的
标签: forms reactjs redux jestjs redux-form