Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Jest testing for form validation errors?

I am trying to test a login form validation errors:

<Form className='form' onSubmit={onSubmit} data-testid='form'>
<FormGroup className='form-group'>
      <input
        type='email'
        placeholder='Email Address'
        name='email'
        value={email}
        onChange={onChange}
        required
      />
    </FormGroup>
    <FormGroup className='form-group'>
      <input
        type='password'
        placeholder='Password'
        name='password'
        value={password}
        onChange={onChange}
        minLength='6'
      />
    </FormGroup>
    <input type='submit' value='Login' />
  </Form>

but the problem is i am unable to get the error text in the component = render()

my test is as follows:

it('validate user inputs, and provides error messages', async () => {
    const { getByTestId, getByText, getByPlaceholderText } = component
    
    fireEvent.change(screen.queryByPlaceholderText(/Email Address/i), {
        target: {value: ""},
    });

    fireEvent.change(screen.queryByPlaceholderText(/Password/i), {
        target: {value: ""},
    });

    fireEvent.submit(getByTestId("form"));

    expect(getByText("Please fill out this field.")).toBeInTheDocument();


})

I am using react testing library with jest

like image 765
Mahmood Ahmed Khan Avatar asked Jul 25 '26 19:07

Mahmood Ahmed Khan


1 Answers

The text displayed on submit is drawn by the browser, not by DOM, so it cannot be inspected with JavaScript.

You may need to add a JavaScript handler for that to sync the actual text to the DOM.

const [errorText, setErrotText] = React.useState("");

const handleInvalid = () => {
  setErrorText("Please fill out this field.");
};

const handleValid = () => {
  setErrorText("");
};

return (
  <input onInvalid={handleInvalid} onValid={handleValid} />
);

Or, you can check the detailed error type by inspecting the ValidityState by accessing element.validity of the input element.

DOM validation is accessible regardless of the testing framework or forms library you use.

For example:

expect(getByPlaceholder("Password").validity.tooShort).toBe(false);
like image 121
Hyeseong Avatar answered Jul 27 '26 12:07

Hyeseong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!