使用React Testing库提交带有数据的单元测试表格
我有一个带有表单的react组件.如果表单提交了正确的数据,我想进行单元测试(使用笑话和RTL).这是我的组件和单元测试方法:
I have a react component with a form. I want to unit test (using jest and RTL) if form gets submitted with correct data. Here are my component and unit test method:
组件:
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
获取文本框值.我在上面的代码中做错了吗?需要解决此问题的帮助.
However, in handleOnSave()
, I get error as deviceName
is undefined
. For some reason, it is not able to get the textbox value from event.target
. Am I doing something wrong in above code? Needed help in fixing this issue.
尝试直接从 event.target
访问输入的问题.您应该改为从 event.target.elements
访问它:
The problem you have it with trying to access the input directly from event.target
. You should access it from event.target.elements
instead: 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);
}
这是您的测试:
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));
});
I created a codesandbox where you can see this in action: https://codesandbox.io/s/form-submit-react-testing-library-45pt8?file=/src/App.js