I'm trying to unit test with React Testing Library a form submission function, however my button to submit the form is outside of the form itself, but is linked via the form=... attribute.
Here is an example test that is failing:
it('my test', () => {
const formSubmit = jest.fn(() => console.log('/// Form submitted ///'));
render(<div>
<form id="test-form" onSubmit={formSubmit}>
<button type="submit">Inside form</button>
</form>
<button form="test-form" type="submit">Outside form</button>
</div>);
// Running this line DOES print the console log correctly
// userEvent.click(screen.getByText('Inside form'));
// This line DOES NOT print the console log...
userEvent.click(screen.getByText('Outside form'));
// Clicking the outside button means this also fails.
expect(formSubmit).toHaveBeenCalled();
});
Is there something I am missing here?
Update
After a lot of Googling it seems that this issue was caused by me using an older version of JEST for my testing.
It was noted on this GIT issue that there was an issue with older versions of JSDOM that caused this.
This particular issue is likely caused by using older jsdom environments (via jest). The bug was fixed in jsdom/jsdom#2369 which was released in jsdom@12.2.0
It looks like I was using "@testing-library/jest-dom": "^5.12.0" but upgrading to the latest ^5.16.2 doesn't seem to have fixed the issue.