Test an onClick event using the React Testing Library

Today we will show you how to test an onClick event using the React Testing Library. Here, we will use the fireEvent.click() to handle the button click event.

In the previous articles, we learned how to write test cases for react application using React Testing Library.

We have also checked a checkbox using the testing library and handle a checkbox event.

Output: Unit Testing

Output - Test an onClick event using the React Testing Library - Clue Mediator
Output – Test an onClick event using the React Testing Library – Clue Mediator

Test an onClick event using the React Testing Library

  1. Create a counter app
  2. Write a test cases
  3. Output

1. Create a counter app

Let’s create a simple counter application using the create-react-app and increment/decrement the counter using button click.

Look at the following component for the counter app.

App.js

2. Write a test cases

Let’s test the following test cases for the counter application. Here, we will mostly focus on the button click event. You may also check this article for other test cases.

  • display counter text

    Assert

    • Counter text should have 0 value
  • increment counter

    Assert

    • Counter should have a value of 1 after clicking the increment
  • decrement counter

    Assert

    • Counter should have a value of -1 after clicking the decrement
App.test.js

3. 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 *