我有一个带表单的react组件,我想进行单元测试(使用jest和RTL),看看表单是否能以正确的数据提交。我想进行单元测试(使用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
是 undefined
. 由于某些原因,它无法从 event.target
. 我是不是在上面的代码中做错了什么?需要帮助解决这个问题。
你的问题是,你试图直接访问来自 event.target
. 你应该从 event.target.elements
而不是。https:/developer.mozilla.orgen-USdocsWebAPIHTMLFormElementelements。.
function handleOnSave(event) {
event.preventDefault();
const { deviceName } = event.target.elements;
const formData = {
deviceName: deviceName.value
};
// this will log the correct formData even in tests now
console.log(formData);
this.props.onSave(formData);
}
这里是你的测试。
it("Test form submit and validation", () => {
const { getByPlaceholderText, getByText } = render(<App />);
const deviceNameInput = getByPlaceholderText(/device name/i);
fireEvent.change(deviceNameInput, { target: { value: "AP VII C2230" } });
fireEvent.click(getByText(/Save Device/i));
});
我创建了一个codesandbox,你可以看到它的运行。https:/codesandbox.iosform-submit-react-testing-library-45pt8? file=srcApp.js。