Logeshkumar
Logeshkumar

Reputation: 131

Unit test jest enzyme throws error on Formik 'resetForm'

I am trying to run unit test (enzyme) throws error on Formik 'resetForm'.

TypeError: Cannot read property 'resetForm' of undefined

FormikForm.js

_handleSubmitPress = (values, { resetForm }) => {
        const { onSubmit } = this.props;

        if (onSubmit) {
            onSubmit({ ...values, resetForm });
        }
    };

UnitTest.js:

it('Should fire formik form submit', () => {
    const UpdateButtonPressMock = jest.fn();
    const component = Component({
        onSubmit: UpdateButtonPressMock,
    });
    expect(component.find(Formik)).toHaveLength(1);
    component.find(Formik)
        .first()
        .simulate('Submit');
    expect(UpdateButtonPressMock).toHaveBeenCalled();
});

I couldn't find any solution for this error.

Could someone help me on the above? I would really appreciate any help.

Upvotes: 0

Views: 734

Answers (1)

piouson
piouson

Reputation: 4565

According to official docs for simulate, the function signature accepts an optional mock event.

The code you are testing uses properties that are not included in the default SyntheticEvent object that ReactWrapper passes to your event handler by default, for instance event.resetForm.

One way to do this is by triggering Formik's onSubmit directly like so:

// UnitTest.js
.simulate("submit", { resetForm: whateverYourMockResetFormValueShouldBe })
component.find(Formik)
  .first()
  .prop('onSubmit')(valuesMock, { resetForm: UpdateButtonPressMock });
expect(UpdateButtonPressMock).toHaveBeenCalled();

I haven't tested this, but you should be able to pass the event along with simulate as well.

// UnitTest.js
component.find(Formik)
  .first()
  .simulate("submit", { resetForm: UpdateButtonPressMock })
expect(UpdateButtonPressMock).toHaveBeenCalled();

Upvotes: 1

Related Questions