我整理了一个非常基本的联系表格,效果很好。但是,现在我需要开始编写单元测试,并且遇到了很多问题(例如,我实际上只能设法使快照测试通过)。
因此,首先,如果您未填写所有必填部分,则我将尝试测试表单在单击“提交”按钮时应呈现我的验证消息。
我认为我可以通过调用handleSubmit()
函数来实现此目的,例如:
componentRender.find('Formik').instance().props.handleSubmit(badFormValues, { resetForm });
但是,当我运行componentRender.debug()
时,不会呈现我的验证消息。就像没有调用validateSchema函数吗?
是否需要做一些特别的事情?我觉得mapPropsToValues()
函数正在工作,从查看状态对象开始,它是用我传递的值填充的。我只是看不到为什么似乎跳过了验证?
我已经参加了2天了,并且无法通过google找到任何好的示例(可能是我的错),所以任何帮助将不胜感激。
作为参考,这里是到目前为止的测试文件:
import React from 'react';
import { shallow, mount } from 'enzyme';
import { BrowserRouter as Router } from 'react-router-dom';
import PartnerRegistrationForm from 'Components/partner-registration-form/PartnerRegistrationForm';
describe('PartnerRegistrationForm component', () => {
const formValues = {
companyName: 'some company',
countryCode: 'GB +44',
telNumber: 12345678,
selectCountry: 'United Kingdom',
postcode: 'ABC1 234',
addressSelect: '123 street',
siteName: 'blah',
siteURL: 'https://www.blah.com',
contactName: 'Me',
email: 'me@me.com',
};
const componentShallow = shallow(<PartnerRegistrationForm {...formValues} />);
describe('Component Snapshot', () => {
it('should match stored snapshot', () => {
expect(componentShallow).toMatchSnapshot();
});
});
describe('Component functionality', () => {
it('should not submit if required fields are empty', () => {
const badFormValues = {
companyName: 'some company',
countryCode: 'GB +44',
telNumber: 12345678,
};
const resetForm = jest.fn();
const componentRender = mount(
<Router>
<PartnerRegistrationForm {...badFormValues} />
</Router>,
);
componentRender.find('Formik').instance().props.handleSubmit(badFormValues, { resetForm });
// console.log(componentRender.update().find('.validation-error'));
// console.log(componentRender.find('Formik').instance());
// expect(componentRender.find('.validation-error').text()).toEqual('Company Name is required');
});
});
});
这是我的withFormik()
函数:
const WrappedFormWithFormik = withFormik({
mapPropsToValues({
companyName,
countryCode,
telNumber,
selectCountry,
postcode,
addressSelect,
siteName,
siteURL,
contactName,
email,
}) {
return {
companyName: companyName || '',
countryCode: countryCode || '',
telNumber: telNumber || '',
selectCountry: selectCountry || '',
postcode: postcode || '',
addressSelect: addressSelect || '',
siteName: siteName || '',
siteURL: siteURL || '',
contactName: contactName || '',
email: email || '',
};
},
validationSchema, // This is a standard Yup.object(), just importing it from a separate file
handleSubmit: (values, { resetForm }) => {
console.log('submitting');
const {
companyName,
countryCode,
telNumber,
selectCountry,
postcode,
addressSelect,
siteName,
siteURL,
contactName,
email,
} = values;
const emailBody = `Name: ${contactName},`
+ `Email: ${email},`
+ `Company Name: ${companyName},`
+ `Country Code: ${countryCode},`
+ `Telephone Number: ${telNumber},`
+ `Country: ${selectCountry},`
+ `Postcode: ${postcode},`
+ `Address: ${addressSelect},`
+ `Website Name: ${siteName},`
+ `Website URL: ${siteURL}`;
// TODO set up actual contact submit logic
window.location.href = `mailto:test@test.com?subject=New partner request&body=${emailBody}`;
resetForm();
},
})(PartnerRegistrationForm);
答案 0 :(得分:2)
如果您尝试通过单击带有type="submit"
的按钮来提交表单,则可能不起作用
我发现让它提交(从而运行验证)的唯一方法是直接模拟它:
const form = wrapper.find('form');
form.simulate('submit', { preventDefault: () => {} });
...此外,在formik的异步验证和状态更改之后,您可能需要使用类似以下的内容来更新包装器:
setTimeout(() => {
wrapper.update();
}, 0);
别忘了使用done()
或异步等待,这样测试不会尽早终止。
答案 1 :(得分:0)
你可以直接使用prop(key)
wrapper.find(Formik).prop('onSubmit')(args)
wrapper.find(Component).prop('onSubmit')(args)
您还可以使用 simulate(event)
onclick
const mockHandleSubmit = jest.fn()
const wrapper = shallow(<Form onSubmit={mockHandleSubmit} />)
wrapper.find(SubmitButton).simulate('click')
expect(mockHandleSubmit).toHaveBeenCalled();