Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test form submission in React with Jest and Enzyme? Cannot read property 'preventDefault' of undefined

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

enter image description here

The handleSubmit function

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.

like image 750
Leon Gaban Avatar asked Jun 07 '17 17:06

Leon Gaban


1 Answers

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);
    });
});
like image 150
Leon Gaban Avatar answered Sep 20 '22 20:09

Leon Gaban