我想测试下面的简单表格。我可以轻松地使用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>
所以我写了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();
});
但是,我的console.log
显示输入未更改,这意味着button
仍为disabled
,因此无法单击它。因此,expect
失败,因为从未提交handleSubmitMock
,因此从未调用form
函数。
这里是带有相同代码的CodeSandbxox。
模拟的click
调用不能正确传播表单中的submit
事件,因此您必须明确地模拟submit
事件来触发它。为了提交表单,您需要将button.simulate('click')
更改为button.simulate('submit')
。