首页 > 解决方案 > 测试 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} />

标签: jestjsreact-final-form

解决方案


我无法使用 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',
    });
  });

推荐阅读