-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Closed
Labels
jsdomIssue with JSDOM environmentIssue with JSDOM environment
Description
@testing-library/react
version: 10.0.2- Testing Framework and version: Jest 26.1.0
- DOM Environment: jsdom via jest - 5.5.0
Relevant code or config:
import React, {useState} from 'react'
import {render, fireEvent} from '@testing-library/react'
const Form = ({submitHandler}) => {
const [inputValue, setInputValue] = useState('')
const handleFormSubmit = e => {
console.log('submit handler invoked. event: ', e)
submitHandler()
}
return (
<form onSubmit={handleFormSubmit} data-testid="form_node">
<input
type="text"
value={inputValue}
onChange={e => setInputValue(e.target.value)}
data-testid="required_input_node"
required
/>
<button data-testid="button_node" type="submit">
Submit
</button>
</form>
)
}
test('submit handler does not get invoked if form is invalid', () => {
const callback = jest.fn()
const {queryByTestId} = render(<Form submitHandler={callback} />)
const form = queryByTestId('form_node')
const input = queryByTestId('required_input_node')
const button = queryByTestId('button_node')
/* the form shoudl be invalid - there's a required input with no value*/
expect(form).not.toBeValid()
/* the input should be invalid - it's required and empty */
expect(input).not.toBeValid()
/* the callback has not been invoked incorrectly yet */
expect(callback).toHaveBeenCalledTimes(0)
/* let's click the submit button */
fireEvent.click(button)
/* this test fails - why???????? */
expect(callback).toHaveBeenCalledTimes(0)
})
What you did:
Wrote a test for a form submit handler callback. Test failed.
What happened:
Reproduction:
https://codesandbox.io/s/relaxed-pine-twqqc?file=/src/__tests__/form.js
Problem description:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
This document indicates:
Trying to submit a form that does not pass validation triggers an invalid event. In this case, the validation prevents form submission, and thus there is no submit event.
However, the submit event for this test does get triggered.
The test event listeners should behave the same as real life event listeners.
Suggested solution:
I'd love to see how event listeners are registered. That's all I can think of at the moment.
germanfr, dwjohnston, mithi and ChaseMillers
Metadata
Metadata
Assignees
Labels
jsdomIssue with JSDOM environmentIssue with JSDOM environment