Test an input field using the React Testing Library

Today, we will show you how to test an input field using the React Testing Library. Here we will use the userEvent.type() method from the @testing-library/user-event npm package.

In this react article, we will create a component where we will add the email input field and handle the validation message based on the email value.

Demo Application

Output - Test an input field using the React Testing Library - Clue Mediator
Output – Test an input field using the React Testing Library – Clue Mediator

Test an input field using the React Testing Library

  1. Create a sample react app
  2. Write a test cases
  3. Output

1. Create a sample react app

Let’s create a simple react application using the create-react-app and handle an email validation message based on the given input.

Look at the following component for the react app.

App.js

2. Write a test cases

Let’s test the following use cases for the above application.

  • render email input

    Assert

    • The input field should be in the document
    • The input field should have a type email attribute
  • pass valid email to test email input field

    Assert

    • The input field have a valid given value
    • The error message should not be in the document
  • pass invalid email to test input value

    Assert

    • The input field have an invalid given value
    • The error message should be in the document
    • The error message should contain “Please enter a valid email.” text

Here, we will use the userEvent from the @testing-library/user-event to type the text in the input field.

App.test.js

3. Output

Run the following command to test the cases.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *