Redux表单onSubmit在测试中重置空对象

Mar*_*son 5 javascript unit-testing reactjs redux-form

onSubmit处理程序中的值始终是一个空对象.如何将一些值传递给它以便我可以测试追加?

测试:

const store = createStore(combineReducers({ form: formReducer }));

const setup = (newProps) => {
  const props = {
    ...newProps,
  };
  expect.spyOn(store, 'dispatch');

  const wrapper = mount(
    <Provider store={store}>
      <RegisterFormContainer {...props} />
    </Provider>,
  );

  return {
    wrapper,
    props,
  };
};

describe('RegisterFormContainer.integration', () => {
  let wrapper;

  it('should append form data', () => {
    ({ wrapper } = setup());

        const values = {
          userName: 'TestUser',
          password: 'TestPassword',
        };

        expect.spyOn(FormData.prototype, 'append');

        // Passing values as second argument DOESN'T work, it's just an empty object
        wrapper.find('form').simulate('submit', values);

        Object.keys(values).forEach((key) => {
          expect(FormData.prototype.append).toHaveBeenCalledWith(key, values[key]));
        });

        expect(store.dispatch).toHaveBeenCalledWith(submit());
    });
});
Run Code Online (Sandbox Code Playgroud)

容器:

const mapDispatchToProps = dispatch => ({
  // values empty object
  onSubmit: (values) => {
    const formData = new FormData();

    Object.keys(values).forEach((key) => {
      formData.append(key, values[key]);
    });

    return dispatch(submit(formData));
  },
});

export default compose(
  connect(null, mapDispatchToProps),
  reduxForm({
    form: 'register',
    fields: ['__RequestVerificationToken'],
    validate: userValidation,
  }),
)(RegisterForm);
Run Code Online (Sandbox Code Playgroud)

零件:

const Form = ({ error, handleSubmit }) => (
  <form onSubmit={handleSubmit} action="">
    <Field className={styles.input} name="username" component={FormInput} placeholder="Username" />

    <button type="submit">
      Register
    </button>
  </form>
);
Run Code Online (Sandbox Code Playgroud)

jak*_*kee 2

这里的问题是您忽略了实际表单的工作原理。如果您尝试submit在表单上模拟事件,则需要在 redux 存储中存储实际的表单值,以便 redux-form 提取这些值并将它们传递给处理程序onSubmit。

根本问题是您不应该redux-form在单元测试中测试端到端的功能。测试您的应用程序是否端到端工作应该在集成测试级别进行。

在这种情况下我的建议是

  1. 假设只要您redux-form正确使用,表单到商店的集成就可以发挥作用。
  2. 编写测试以确保传递给redux-form相关组件的函数和值正确且正常工作。
  3. 保持测试组件和容器之间的分离,本文应该为您提供有关如何测试连接的组件的一个很好的概述

因此,请进行mapDispatchToProps彻底的测试,以确保它生成的函数的行为符合您的预期。然后确保将正确的函数和 props 传递到组件和容器中的正确位置。之后,您可以放心地假设只要您正确使用 redux 和 redux-form ,一切都会正常。

希望这可以帮助!