Sak*_*ket 12 unit-testing reactjs jestjs react-testing-library
我有一个带有表单的反应组件。我想对表单是否使用正确的数据提交进行单元测试(使用 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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
单元测试:
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));
});
Run Code Online (Sandbox Code Playgroud)
但是,在 中,我按原样handleOnSave()收到错误。由于某种原因,它无法从 获取文本框值。我在上面的代码中做错了什么吗?需要帮助来解决这个问题。deviceNameundefinedevent.target
tud*_*ely 13
尝试直接从 访问输入时遇到的问题event.target。您应该从以下位置访问它event.target.elements:https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements。
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);
}
Run Code Online (Sandbox Code Playgroud)
这是你的测试:
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));
});
Run Code Online (Sandbox Code Playgroud)
我创建了一个codesandbox,您可以在其中看到它的实际效果:https://codesandbox.io/s/form-submit-react-testing-library-45pt8 ?file=/src/App.js