How to Validate React Testing Library Click Button Events

Introduction The React testing library is a powerful library used for testing React components. The library helps generate mock events…

By Testim,

Introduction

The React testing library is a powerful library used for testing React components. The library helps generate mock events to simulate user input and helps query the DOM as a normal user would. It also provides functionalities such as finding form elements by their label text and links and buttons from their text. The testing library can fire events such as a button click or a form submit using the fireEvent function. We’ll get into that more later.

This tutorial assumes you have a working knowledge of React, the MERN stack( MongoDB, Express.js, React and Node.js), and of course, JavaScript. Don’t worry if you’re not super familiar with the MERN stack; I try to give as much detail as you’ll need.

Building a To-do List App Using the MERN Stack

We’ll try to build a simple to-do list app that stores to-do list. Here’s a brief idea of what it will look like.

react testing library click button

It consists of an input textbox at the top of the to-do area, with an add button that allows you to add tasks. Each task has a checkbox and a delete button. The checkbox helps you update the status of your to-do list. The delete button helps delete a to-do item from the database.

The application will perform CRUD operations, including Create, Read, and Update. We’ll first briefly go through the server-side code, in Express.js and MongoDB, and then the front-end code, in React.

You have to install Mongoose, Express and CORS (cross-origin resource sharing)  libraries. Mongoose connects with your local MongoDB server, and it requires you to start your MongoDB server before running Server.js. If you’re new to MongoDB, this guide on setting up and running MongoDB on your computer should help.

Server.js 

The file above uses Express.js to handle requests and responses and uses Mongoose to connect to the database. Then we set up CORS to allow our react application to access the server API. Next, we define the schema, which is the structure of the database so that MongoDB know to expect documents with the a specific structure. We also define routes, which we use to associate a URL with a certain function. You can use the index route for API communication with the React application and the /listener route to listen to GET requests from the React application. Lastly, with app. listen(), we run the server on port 5000 and listen to requests. To run the server, type node server.js. On successful execution, it displays: “todo_app server listening on port 5000.”

Index.html

index.css 

This is the code for the index.html and index.css programs. If you click on index.html, it should look something like this:

react testing library click button

Now we start building our front end in React. We’re running React using npm, as recommended by the React team. Let us jump right into it.

App.css

We added the CSS component to React elements, which we’ll render in App.js. The iptext class corresponds to the input textbox element, where we’ll enter our to-do task. The img_ip class is the submit element; clicking it sends data to the server and the  /listener route then handles the data.

App.js

Here, we import React, useEffect and useState from the React library. We also import the App.css file. After that, we initialize useState to receive data from the fetch function; later, we iterate data_output at return by mapping the keys and values. We also create a reference object to get data from the input textbox with the className iptext. Next, we initialize the useEffect function and write our main fetch function inside it. The output has the form of an array of JSON documents. We convert the array into a single object and pass it to the useState object setData, which is later parsed from data_output. Then we declare subfunctions add_data, bool and del to communicate with the server. Lastly, we return the elements. the li tag is parsed inside the object iteration.

Now we have finally finished our simple MERN to-do application. To see it in action we’ll run both Server.js and React together. You can run them from multiple command prompt instances. Server.js displays an empty array and React displays nothing. You can add to-do lists in your application and see the updated data in the database by running http://localhost:5000. You’ve now successfully built a MERN to-do application. Let’s move on to the testing part, using the React testing library.

App.test.js

Here, we run a simple test to see if our application can add to-do items to our React application without any errors. To run the test, run npm test at your command prompt.

To do this, we first import the ReactDOM.render function, render. This function renders your application inside the test case. The screen function gives you access to the rendered DOM and fireEvent mimics user input to click events. We import this from the React testing library, which comes preinstalled with React.

Next, we initialize the test function. We used an async function in our test so that we can use await in our test function.

Then we render our application by passing App to render

We define the DOM elements iptext and add_button and use queryByAltText to query the DOM for the tag and return the DOM elements. Now we can use fireEvent by referencing iptext and add_button.

The code above simulates user input by changing the value of the input text box to testip.

Now we trigger the onClick event by simulating a click in the image img1. This sends the input textbox data to the server using the fetch function declared in App.js and the database gets updated with our previous fireEvent text. Notice that the test passed successfully.

Congrats! You made a MERN to-do application and tested if you can add to-do tasks to your application.

You can find the files from the tutorial here on Github.

Conclusion

As you build more complicated applications, the test cases will also become more complex. Keep learning and experiment with different and more complex test cases. I wish the best to everyone reading this! Have a great day ahead! If you want to learn more about React Native testing, check out this blog.

Expand Your Test Coverage

Fast and flexible authoring of AI-powered end-to-end tests — built for scale.
Start Testing Free

Testim's latest articles, right in your inbox.

From our latest feature releases, to the way it impacts the businesses of our clients, follow the evolution of our product

Blog Subscribe