I'm writing a test to check if the error Notification component displays if the login form is submitted with no data.
describe('User signin', () => {
it('should fail if no credentials are provided', () => {
const loginComponent = shallow(<Login />);
expect(loginComponent.find('.form-login').length).toBe(1);
loginComponent.find('.form-login').simulate('submit');
expect(loginComponent.find(Notification).length).toBe(1);
});
});
It looks like the .simulate
is working as the test reaches my handleSubmit
function, however I am running into this error in the test:
TypeError: Cannot read property 'preventDefault' of undefined
handleSubmit(e) {
e.preventDefault(); // <-- problem here
const user = this.state.username;
const pass = this.state.password;
const gotoDashboard = () => this.props.history.push('/dashboard');
const postLogin = (user, pass) => {
api.userLogin(user, pass)
My test will past if I remove the e.preventDefault();
line, however I need that line in there to prevent the default form submission event.
Figured it out quickly... I just needed to create a fakeEvent with a fake preventDefault function and pass it along:
describe('User signin', () => {
it('should fail if no credentials are provided', () => {
const fakeEvent = { preventDefault: () => console.log('preventDefault') };
const loginComponent = shallow(<Login />);
expect(loginComponent.find('.form-login').length).toBe(1);
loginComponent.find('.form-login').simulate('submit', fakeEvent);
expect(loginComponent.find(Notification).length).toBe(1);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With