单元测试 jest enzyme 在 Formik 上抛出错误 'resetForm'
Unit test jest enzyme throws error on Formik 'resetForm'
我正在尝试 运行 单元测试(酶)在 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();
});
我找不到解决此错误的方法。
有人可以帮我解决以上问题吗?如果有任何帮助,我将不胜感激。
根据 official docs for simulate
,函数签名接受一个可选的模拟事件。
您正在测试的代码使用的属性未包含在默认 SyntheticEvent
对象中,默认情况下 ReactWrapper
传递给您的事件处理程序,例如 event.resetForm
.
一种方法是直接触发 Formik 的 onSubmit
,如下所示:
// UnitTest.js
.simulate("submit", { resetForm: whateverYourMockResetFormValueShouldBe })
component.find(Formik)
.first()
.prop('onSubmit')(valuesMock, { resetForm: UpdateButtonPressMock });
expect(UpdateButtonPressMock).toHaveBeenCalled();
我还没有测试过这个,但是你应该也可以通过模拟来传递事件。
// UnitTest.js
component.find(Formik)
.first()
.simulate("submit", { resetForm: UpdateButtonPressMock })
expect(UpdateButtonPressMock).toHaveBeenCalled();
我正在尝试 运行 单元测试(酶)在 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();
});
我找不到解决此错误的方法。
有人可以帮我解决以上问题吗?如果有任何帮助,我将不胜感激。
根据 official docs for simulate
,函数签名接受一个可选的模拟事件。
您正在测试的代码使用的属性未包含在默认 SyntheticEvent
对象中,默认情况下 ReactWrapper
传递给您的事件处理程序,例如 event.resetForm
.
一种方法是直接触发 Formik 的 onSubmit
,如下所示:
// UnitTest.js
.simulate("submit", { resetForm: whateverYourMockResetFormValueShouldBe })
component.find(Formik)
.first()
.prop('onSubmit')(valuesMock, { resetForm: UpdateButtonPressMock });
expect(UpdateButtonPressMock).toHaveBeenCalled();
我还没有测试过这个,但是你应该也可以通过模拟来传递事件。
// UnitTest.js
component.find(Formik)
.first()
.simulate("submit", { resetForm: UpdateButtonPressMock })
expect(UpdateButtonPressMock).toHaveBeenCalled();