How to test onSubmit in react-testing-library
Click on the submit button isn't working. How to test it properly?
I have a form component that I want to test Form.js
:
function Form(props) {
return (
<form onSubmit={props.onSubmit}>
<button type="submit">Submit</button>
</form>
);
}
(Subscribe to my Monthly Newsletter to get info about new posts on this blog.)
Because I've heard a lot about react-testing-library that's what we're going to use in Form.test.js
:
import React from "react";
import { render, fireEvent } from "react-testing-library";
import Form from "./Form";
it("submits", () => {
const onSubmit = jest.fn();
const { getByText } = render(<Form onSubmit={onSubmit} />);
fireEvent.click(getByText("Add"));
expect(onSubmit).toHaveBeenCalled();
});
Please take a look at react-testing-examples.com/jest-rtl if you notice that there is no call to
cleanup
Unfortunately, I get an error:
console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Not implemented: HTMLFormElement.prototype.submit
That's weird. It even seems to be used in the examples I've found for testing forms.
Workaround: #
I've worked around it by firing submit
on the form itself. See new Form.test.js
:
import React from "react";
import { render, fireEvent } from "react-testing-library";
import Form from "./Form";
it("submits", () => {
const onSubmit = jest.fn();
const { getByTestId } = render(<Form onSubmit={onSubmit} />);
fireEvent.submit(getByTestId("form"));
expect(onSubmit).toHaveBeenCalled();
});
Difference:
const onSubmit = jest.fn();
- const { getByText } = render(<Form onSubmit={onSubmit} />);
- fireEvent.click(getByText("Add"));
+ const { getByTestId } = render(<Form onSubmit={onSubmit} />);
+ fireEvent.submit(getByTestId("form"));
expect(onSubmit).toHaveBeenCalled();
Please remember to add data-testid
to your Form.js
:
function Form(props) {
return (
<form onSubmit={props.onSubmit} data-testid="form">
<button type="submit">Submit</button>
</form>
);
}
return (
- <form onSubmit={props.onSubmit}>
+ <form onSubmit={props.onSubmit} data-testid="form" >
<button type="submit">Submit</button>
</form>
);
});
Now you can build on top of the test.
(If you like this post and want to learn JavaScript then subscribe to my Learn JS Newsletter)
Want to learn more?
Sign up to get a digest of my articles and interesting links via email every month.