jestjs - 测试 react-final-form 提交
问题描述
我已经开始从 redux-form 迁移到 react-final-form 以使我的包更小。我对我的表单进行了一些测试,其中之一是测试表单提交时是否调用了正确的操作。切换到 react-final-form 后,我的测试中的存储操作永远不会被调用。
当表单作为属性传递时,有没有办法测试提交功能。
我的测试:
it('submits the form', () => {
const wrapper = shallowUntilTarget(<LoginFormContainer store={store} />, 'form');
wrapper.find('form').simulate('submit');
expect(store.getActions()).toEqual(expect.arrayContaining([{ formObj: {}, type: 'PATIENT_LOGIN_REQUEST' }]));
});
shallowUntilTarget 通过容器渲染实际的表单
被测组件:
class LoginForm extends React.Component<Props> {
submitForm = (values) => {
this.props.dispatch(actions.loginPatient(values));
};
render() {
return (
<Form
onSubmit={this.submitForm}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit} />
解决方案
我无法使用 redux-form 测试验证,但实际上在 react-final-form 中执行起来要容易得多。当验证不成功时,表单不会提交并失败。我的 LoginForm 有电子邮件和密码验证
<Form
onSubmit={this.submitForm}
validate={createValidator({
email: [required, email],
password: [required, minLength('8')],
})}
render={({ handleSubmit }) => (
可能有两个测试。一次测试失败,一次测试成功提交。它们都必须发生在已安装的组件上。
it('does not submits invalid form ', () => {
const wrapper = mount(<LoginFormContainer store={store} />);
wrapper.find('form').simulate('submit');
expect(store.getState().lastAction).not.toEqual({ payload: {}, type: 'PATIENT_LOGIN_REQUEST' });
});
it('submits valid form', () => {
const wrapper = mount(<LoginFormContainer store={store} />);
const email = wrapper.find('input[name="email"]');
email.instance().value = 'cerny@seznam.cz';
email.simulate('change', email);
const password = wrapper.find('input[name="password"]');
password.instance().value = '12345678';
password.simulate('change', password);
wrapper.find('form').simulate('submit');
expect(store.getState().lastAction).toEqual({
payload: { email: 'cerny@seznam.cz', password: '12345678' },
type: 'PATIENT_LOGIN_REQUEST',
});
});
推荐阅读
- algorithm - 有向图中的欧拉电路
- python - How To Clear a Label Assigned to a Grid in Specific Scenario Tkinter
- websphere - 在 WAS 中创建集群服务器
- bash - 在bash中使用while循环匹配行的问题
- firebase - PlatformException(ERROR_INVALID_EMAIL,电子邮件地址格式错误。,null)
- pine-script - 我只能在我的编码脚本中添加最多 5 个脚本
- node.js - 无法从 Broker 中的 MQTT 消息解析 JSON
- javascript - 如何在html表格中检测元素并分组
- javascript - 如何获取在 Javascript 中拆分我的字符串的分隔符?
- c# - 如何修改 ASP.NET Core 中的默认 Authorize 属性?