Skip to content

Submit event handler fires even if form is invalid #729

@marcgarygray

Description

@marcgarygray
  • @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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsdomIssue with JSDOM environment

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions