I am trying to test a Redux action and need assistance with testing an action with side-effects.
Here is my action :
export function login(email, password) {
return dispatch => {
dispatch(setLoginSuccess(false));
loginApi(email, password, error => {
dispatch(setLoginPending(false));
if (!error) {
dispatch(setLoginSuccess(true));
} else {
dispatch(setLoginError(error));
}
});
}
}
Below is the loginApi function to authenticate user :
export function loginApi(email, password, callback) {
if (email === '[email protected]' && password == '123') {
return callback(null);
} else {
return callback(new Error('Please provide valid email and password'));
}
};
Additionally, I am facing an issue while simulating a form submit in my component with Enzyme and Jest.
Here is the code for the same :
render() {
let {email, password, emailValid} = this.state;
let {isLoginPending, isLoginSuccess, loginError} = this.props;
return (
<div className="col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2 col-xs-10 col-xs-offset-1">
<h3 className="text-center">Login</h3>
<form className="login-form" onSubmit={this.handleSubmit.bind(this)}>
<div className={emailValid? "form-group has-success" : (emailValid == undefined)? "form-group": "form-group has-error"}>
<label>Email address</label>
<input type="email" name="email" className="form-control" ref="userEmail"
placeholder="Enter your email" onChange={this.handleChange.bind(this)}/>
</div>
{/* Checking if email valid or not */}
{this.props.emailValid? "" : (this.props.emailValid == undefined)? "" : <p className="text-danger">Please provide a valid email!</p>}
<div className="form-group">
<label>Password</label>
<input type="password" name="password" className="form-control" ref="userPassword"
placeholder="Enter your password" onChange={this.handleChange.bind(this)}/>
</div>
<button type ="submit" className="btn btn-primary btn-block" disabled={!this.props.emailValid}>Get Started</button>
{/* Displaying error messages */}
{ loginError && <div className="auth-error-msg"><p className="text-danger">{loginError.message}</p></div> }
</form>
</div>
);
};
Here is the code for the handleSubmit event:
handleSubmit(e){
e.preventDefault();
this.props.login(this.refs.userEmail.value, this.refs.userPassword.value);
this.setState({
email: '',
password: ''
});
}
I am trying to simulate the Submit event in this way :
it('should render 1 error block on submitting invalid form', () => {
// Render a checkbox with label in the document
const spy = jest.fn();
const component = shallow(<Login login={spy}/>);
const form = component.find('form').simulate('submit');
});
But it currently throws an error as it cannot find preventDefault. How do I test this event?