Check a Checkbox using React Testing Library

Today we’ll show you how to check a checkbox using React Testing Library.

In the previous article, we had learned about the normal test cases using React Testing Library. Here, we will write a test case for the checkbox type and for that we will create a simple react application to show/hide the div element.

Output: Unit Testing

Output - Check a Checkbox using React Testing Library - Clue Mediator
Output – Check a Checkbox using React Testing Library – Clue Mediator

Unit testing for a Checkbox using React Testing Library

  1. Create a react application
  2. Create a toggle app
  3. Write a test cases
  4. Output

1. Create a react application

Let’s create a startup react application using the create-react-app NPM package. Run the following command to create a react app.

2. Create a toggle app

Now, we will create a toggle application, where we will add the checkbox input type and div elements on the page. Here, we will show/hide the div by selecting the checkbox input.

App.js
index.css

Output

App Output - Check a Checkbox using React Testing Library - Clue Mediator
App Output – Check a Checkbox using React Testing Library – Clue Mediator

3. Write a test cases

We will test the following use case for the App.js component.

  • render component

    Assert

    • The checkbox should be in the document
    • The checkbox should be unchecked by default
    • The box element should be hidden
  • toggle element by selecting checkbox

    Assert

    • Execute the click event of the checkbox
    • The checkbox should be checked after the click
    • The box element should be visible
    • Execute the click event again
    • The checkbox should be unchecked
    • The box element should be hidden

Here we will use the @testing-library/user-event package to handle the click event.

App.test.js

4. Output

Run the following command to test the cases.

I hope you find this article helpful.
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 *