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:
Component:
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>
);
}
}
Unit Test:
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));
});
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.
test
? Why we can't just use the.
with theinput
id
as we would in the browser? – Dobbin