[英]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
演示相同的测试。
<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("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.