Home > front end >  React Testing Library Submits Form Even if Required Inputs are Empty
React Testing Library Submits Form Even if Required Inputs are Empty

Time:02-10

Problem

If required Inputs are empty on the form, submit button shouldn't work. This is the nature of it when the user physically interacts with it. But in the testing environment, the button submits without checking the form for required Inputs. This is the case when using "Simulate.click" or "fireEvent.click". I have found other forms talking about this issue, but haven't found a solution to it. I was wondering if there was a solution to this or maybe I'm going about something the wrong way. Thanks.

Code

       <form onSubmit={handleSubmit}>
            <h1>Contact Us</h1>
            <label htmlFor="name">Name<span className="optional">*</span> 
            </label>
            <input
                className="contact-input"
                type="text"
                name="name"
                id="name"
                value={name}
                onChange={handleChange("name")}
                required
            />

            <button type="submit">Send</button>
      </form>

Test

test("When form is empty, expect submit to not work", () => {
const history = createMemoryHistory();

render(
    <Router>
        <Contact location={history}/>
    </Router>
)

const submitButton = screen.getByRole('button', /send/i)

    // Both Simulate and fireEvent give the same results. 
    Simulate.click(submitButton)
    // fireEvent.click(submitButton)

    screen.debug()
    // I can see the form submitted and the "thank you" Html element is loaded. This should not be the case as required input wasn't filled. 
});

CodePudding user response:

  •  Tags:  
  • Related