我正在写一个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)
});
});
答案 0 :(得分:0)
您需要在
中声明this.props.handleSubmit
function mapDispatchToProps
从上述函数调用的调度方法,相应的调用将进入您的操作文件
答案 1 :(得分:0)
想出来,我在安装组件后宣布我的间谍。在安装组件之前声明间谍修复了问题。