• Whizzystack Solutions

How To Test Your React Apps With The React Testing Library

In this article we will discuss about the automatic testing of written software projects with some types of common testing process. First of all we will build to- do list app by Test-Driven Development (TDD) approach. Here I will use combination of RTL and Jest which were pre- installed in any new project created by Create-React-App (CRA).


At first you need to know the working process of new React project and how to set up and explore it and how to work with yarn package manager (or npm). One should know about Axios and React- Router.


Testing of Code


To hand over a software to the customer you should confirm that whether it satisfy all the specification or not as customer expectance.


Not only at the time of shipping, testing our code is essential for lifetime. There are many reason behind it:


  • We may update some parts of our application by changing the code.

  • A third party may interfere in this.

  • The browser which run the application may undergo breaking changes.

  • Some function may stop due to unexpected reason.

For this reason testing is important throughout lifetime of a project.

Types of Automated Testing


  • Unit test

This test verify the unit of our application which works isolately. For example it test particular function for known input and expected output.


  • Smoke test

It check the system whether up and running or not. For example in a React app we just need to render our main app components which would fairly render the browser.


  • Integration test

It check two or more module works together or not. For example server and database work together or not.


  • Functional test

The test is done to verify functional specifications of the system.


  • Acceptance test

This test is done by business owner whether for the system verification.


  • Performance test

It verify how the system work under load which specify how fast app load in a browser.


Importance of React Testing Library?


The most common React Testing options are Enzyme and React Testing Library (RTL).


RTL


It is very simple that the user need not to care whether you use redux or context for state management. They just fix your app in certain way you want. It just need to usual testing of app.


Advantages

  • It is very easy to use.

  • New React project comes with RTL and Jest configured.

  • Testing is done of your choice

Project Setup

  • To open a terminal follow the command:

# start new react project and start the server
npx create-react-app start-rtl && cd start-rtl && yarn start

While a project running open separate terminal to run yarn test and then press a. Run all the project in watch mode which indicates that when detect changes it automatically run the file. In terminal picture is looked like


  • Green line means in the test we are passing with flying colours.

  • CRA sets up RTL and Jest are for sample test.

  • Jest is javascript testing network to running the test. It is not listed in package.json but can be find from yarn.lock.

  • Jest provide huge range of functionality like assertions, mocking, spying, etc.

There are some packages for testing specifications like:

  • testing-library/jest-dom: provides custom DOM element matchers for Jest.

  • testing-library/react: provides the APIs for testing React apps.

  • testing-library/user-event: provides advanced simulation of browser interactions

Testing And Building The To-Do List Index Page


The components specifications for the system are:

  • A loading indicator

  • Display the title of 15 to do list while returns to the APIs call.

  • To creat a file src/TodoList.js enter the content.


import React from "react";
import "./App.css";
export const TodoList = () => {
 return (
 <div>
 </div>
 );
};

  • Isolation testing is done before incorporating into the app

  • Testing is also done to check any accidental fight fire.

  • To create a new file in src/TodoList.test.js enter the code.


import React from "react";
import axios from "axios";
import { render, screen, waitForElementToBeRemoved } from "./custom-render";
import { TodoList } from "./TodoList";
import { todos } from "./makeTodos";
 
describe("<App />", () => {
 it("Renders <TodoList /> component", async () => {
 render(<TodoList />);
 await waitForElementToBeRemoved(() => screen.getByText(/Fetching todos/i));
 
 expect(axios.get).toHaveBeenCalledTimes(1);
 todos.slice(0, 15).forEach((td) => {
 expect(screen.getByText(td.title)).toBeInTheDocument();
 });
 });
});

The source of to do which can be used in list


const makeTodos = (n) => {
 // returns n number of todo items
 // default is 15
 const num = n || 15;
 const todos = [];
 for (let i = 0; i < num; i++) {
 todos.push({
 id: i,
 userId: i,
 title: `Todo item ${i}`,
 completed: [true, false][Math.floor(Math.random() * 2)],
 });
 }
 return todos;
};
 
export const todos = makeTodos(200);
 

This function generated complete list, from where it is choosen by true and false.

  • Unit test should be done under few seconds where APIs calls are impractical.

  • To avoid APIs calls mocking should be done where original version is replaced by fake version.

  • Jest automatically provide mocking functions in the box.

  • To mock the Axios create a file src/_mocks_/axios.js and enter the below content:

  • Jest originally find the mock folder instead of find the original one.

  • Here we carried out a passing and a failings test.


Testing And Building The Single To-Do Page

  • To creating the list one should make it simplier

  • To add components create a file by src/TodoItem.js and content should added like

import React from "react";
import { useParams } from "react-router-dom";
 
import "./App.css";
 
export const TodoItem = () => {
 const { id } = useParams()
 return (
 <div className="single-todo-item">
 </div>
 );
};

  • The file is the const { id } = useParams() line which is attached from react-router-dom that lets us read URL parameters.

  • Here the situation is little different from the other because the user when click on the link

  • After satisfying we want to hold first item in the to-do list. To prevent collision with other URL, we use the global mock with Jest’s mockImplementationOnce.

The test is finished by adding position where it is expected.

Here we expected to see our name and who created this, but it is not sure about to-do status. Here we can create a switch block, if it is not work we can throw it like an error.


Conclusion


To understand this you need to write tests for React app, no matter how small it is. For better implementation you can use CRA’s testing docs and RTL’s documentation. For small tests make sure that all the components should render. You can continuously add more tests over that time.


We will be happy to answer your questions on designing, developing, and deploying comprehensive enterprise web, mobile apps and customized software solutions that best fit your organization needs.

As a reputed Software Solutions Developer we have expertise in providing dedicated

remote and outsourced technical resources for software services at very nominal cost. Besides experts in full stacks We also build web solutions, mobile apps and work on system integration, performance enhancement, cloud migrations and big data analytics. Don’t hesitate to get in touch with us!

0 views
whizzystack logo

About Us

 

We build & support your own talented, trusted, full-time development team hosted out of Whizzystack’s headquarters in India. We also deliver world class product and software development services Read more

Whizzystack

Our Developers

Contact Us

 New Jersey     

+1(877)3685420

 sid.baker@whizzystack.com 

 

 India   

+91(95)60641297

 +91(120)4287309 

 info@whizzystack.com

Subscribe to Our Blog

Sign up to receive email notifications when Whizzystack drops more knowledge.

  • LinkedIn
  • Facebook
  • Twitter
  • Instagram
  • RSS