我有一个带有表单的react组件。如果表单使用正确的数据提交,我想进行单元测试(使用 jest 和 RTL)。这是我的组件和单元测试方法:
零件:
class AddDeviceModal extends Component {
handleOnSave(event) {
const { deviceName } = event.target;
const formData = {
deviceName: deviceName.value,
};
this.props.onSave(formData);
}
render() {
return (
<Form onSubmit={this.handleOnSave}>
<Form.Label>Device Name</Form.Label>
<Form.Control name="deviceName" placeholder="Device Name" required />
<Button type="submit">Save Device</Button>
</Form>
);
}
}
单元测试:
it("Test form submit and validation", () => {
const handleSave = jest.fn();
const props = {
onSave: handleSave,
};
render(<AddDeviceModal {...props} />);
const deviceNameInput = screen.getByPlaceholderText(/device name/i);
fireEvent.change(deviceNameInput, { target: { value: "AP VII C2230" } });
fireEvent.click(getByText(/save device/i));
});
然而,在handleOnSave()
我得到错误的deviceName
IS undefined
。出于某种原因,它无法从event.target
. 我在上面的代码中做错了什么吗?需要帮助来解决这个问题。