vendredi 25 mai 2018

Bug when simulating click event

I am trying to test input fields in form. However when using Enzyme.js to simulate change in input field the state is incorrectly updated, since the log reveal that simulate function has created new record in state named undefined.I'd be really glad for help.

Regards

Initial component state looks like this:

this.state = {
    submission: {
        firstName: '',
        lastName: '',
        email: '',
        date: new Date(),
        validation: {
            email : {isInvalid: false, message: ""},
            firstName : {isInvalid: false, message: ""},
            isValid : true,
            lastName : {isInvalid: false, message: ""}
        }
    }
}

This is the testing function:

it('should respond to change event and change the state of the Component', () =>{
    const wrapper = shallow(<ApplicationForm/>);
    console.log(wrapper.find('#firstName').debug());

    wrapper.find('#firstName').simulate(
        'change', {
            target: {
                name: 'firstName',
                value: 'John'
            }
        }
    )

    expect(wrapper.state().submission.firstName).to.equal('John');
})

This is what I expect to get in state:

submission: {
    firstName: 'John',
    ...
}

And this is what I get when I inspect result with wrapper.debug

submission: {
    firstName: '',
    lastName: '',
    email: '',
    date: new Date(),
    validation: {
        email : {isInvalid: false, message: ""},
        firstName : {isInvalid: false, message: ""},
        isValid : true,
        lastName : {isInvalid: false, message: ""}
    },
    undefined: 'John'
}

Below you can see the code of the rendered form:

<input type="text"
    id="firstName"
    className="form-control form-control-sm"
    placeholder="First name"
    onChange={this.updateSubmission.bind(this)}
/>

updateSubmission function looks as follows:

updateSubmission(event) {
    let updatedSubmission = Object.assign({}, this.state.submission);

    updatedSubmission[event.target.id] = event.target.value;
    this.setState({
        submission: updatedSubmission
    });
}

Aucun commentaire:

Enregistrer un commentaire