简体   繁体   English

酶测试不改变输入值和提交表格

[英]enzyme test not changing input value and submitting form

I want to test the simple form below.我想测试下面的简单表格。 I was able to easily test it with react-testing-library , but I want to demo the same test with enzyme .我可以用react-testing-library轻松测试它,但我想用enzyme演示相同的测试。

Code代码

<form
  onSubmit={event => {
    event.preventDefault();
    handleSubmit(firstName);
    this.setState({
      firstName: ""
    });
  }}
>
  <label htmlFor="first-name">First Name:</label>
  <input
    id="first-name"
    value={firstName}
    onChange={this.handleChange}
  />
  <button disabled={!firstName} className="primary" type="submit">
    Submit
  </button>
</form>

So I wrote the enzyme test to change the input value then click the submit button .所以我写了enzyme测试来改变input值然后点击submit button

Test测试

test("should submit form when the submit button is pressed", () => {
  const handleSubmitMock = jest.fn();
  const names = [];
  const wrapper = mount(
    <Input handleSubmit={handleSubmitMock} names={names} />
  );
  const input = wrapper.find("#first-name");
  const button = wrapper.find("button.primary");

  input.simulate("change", { target: { value: "Bill" } });
  console.log(input.debug()); // input value unchanged 🤔
  console.log(button.debug()); // button still disabled 🤷‍♂️
  button.simulate("click");

  expect(handleSubmitMock).toHaveBeenCalled();
});

However, my console.log 's are showing that input is not changing which means the button is still disabled so it can not be clicked.但是,我的console.log显示输入没有改变,这意味着该button仍处于disabled因此无法单击。 Therefore, the expect fails because the handleSubmitMock function is never called since the form is never submitted.因此, expect失败是因为handleSubmitMock函数从未被调用,因为form从未被提交。

Here is a CodeSandbxox with the same code to mess around with.这是一个带有相同代码的CodeSandbxox

The simulated click call does not properly propagate the submit event in the form, so you explicitly have to simulate the submit event to trigger it.模拟的click调用没有正确传播表单中的submit事件,因此您必须明确地模拟submit事件来触发它。 In order for the form to submit, you need to change button.simulate('click') to button.simulate('submit') .为了提交表单,您需要将button.simulate('click')更改为button.simulate('submit')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM