Jest Testing React Form提交

时间:2019-12-04 17:08:56

标签: reactjs unit-testing jestjs enzyme

尝试测试React表单提交时出现错误。错误显示为TypeError: Cannot read property 'value' of undefined。我发现其他用户也遇到类似的问题,但是由于我使用的是event.target.elements而不是event.target.value,因此我的用户是独一无二的。

这是我正在测试的功能:

  const handleSubmit = event => {
    event.preventDefault();
    const { createPassword, confirmPassword } = event.target.elements;
    if (createPassword.value !== confirmPassword.value) {
      setPassValidationError("*Passwords must match!");
    } else if (createPassword.value.length < 8) {
      setPassValidationError("*Passwords must be at least 8 characters long!");
    } else if (createPassword.value.search(/[A-Z]/) < 0) {
      setPassValidationError(
        "*Passwords must contain at least one uppercase letter!"
      );
    } else if (createPassword.value.search(/[!@#$%^&*]/) < 0) {
      setPassValidationError(
        "*Passwords must contain at least one special character!"
      );
    } else {
      props.updatePassword({
        uid: props.uid,
        token: props.token,
        new_password: createPassword.value
      });
      event.target.reset();
    }
  };

以下是表单上使用的输入字段:

<input id="create-password" type={passType} required />
<input id="confirm-password" type={passType} required />

现在,当我运行测试时,我期望createPassword.valueconfirmPassword.value接受各自输入字段的模拟数据的值。这是我的测试:

it("passwords must be 8 char long", () => {
  const onMock = jest.fn();
  const wrapper = mount(<NoAuthPasswordChange handleSubmit={onMock} />);
  const passInput = wrapper.find("#create-password");
  const confirmPass = wrapper.find("#confirm-password");
  passInput.simulate("change", { target: { value: "QQQQQQ" } });
  confirmPass.simulate("change", { target: { value: "QQQQQQ" } });
  const form = wrapper.find("#no-auth-password-change-form");
  form.simulate("submit", { preventDefault: () => {} });
  expect(wrapper.find("#password-validation-error").text()).toContain(
    "*Passwords must be at least 8 characters long!"
  );
});

我该怎么做才能使createPassword.value存在?

1 个答案:

答案 0 :(得分:1)

您尝试过这样的事情吗?

form.simulate('submit', {
  preventDefault: () => {},
  target: {
    elements: {
      createPassword: { value: 'blah' },
      confirmPassword: { value: 'some value' }
    }
 });