【问题标题】:Test react-final-form submit测试 react-final-form 提交
【发布时间】:2018-06-15 16:58:48
【问题描述】:

我已经开始从 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} />

【问题讨论】:

  • 快速浏览后,该代码对我来说似乎很好。它不工作?出了什么问题?
  • 它不起作用。 submitForm 函数不会被调用。我认为这是因为 submitForm 是作为属性传递的。
  • 我已经通过切换到mount解决了这个问题。
  • 我看不出有什么明显的问题。 this.submitForm() 根本没有被调用?而在 Redux Form 中模拟提交的那种方式?
  • 这是因为验证器。我在示例中删除了它以使其更清晰,但这并不好。我会尽快提交答案。

标签: jestjs react-final-form


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-12-26
    • 2019-12-02
    • 2021-09-15
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多