How to test React App using Jest
By Mohit Joshi, Community Contributor - September 27, 2023
React’s popularity has multiplied over the past several years as a result of its effectiveness in giving developers the tools they need to make user interfaces and deliver better-than-ever user experiences. Statista figures show more than 40% of developers worldwide use React to create dynamic web applications. Because so many people rely on websites built using React, it presents a challenge to guarantee that our website is error-free and offers everyone who uses it optimal functionality.
This is when testing enters the picture, and one of the most widely used tools for testing React Applications is Jest. In this React Jest tutorial, we are going to understand how to test React applications using Jest.
What is Jest?
Jest is a well-liked testing tool that makes it simple to test JavaScript applications, particularly those created using JavaScript-based frameworks like React. It is an open-source technology that has won the trust of many developers and is supported by the tech giant Facebook.
It has succeeded in becoming more than just a testing tool and has found a place as a crucial element in the developer’s toolkit. It is the reliable option that makes it simple for developers to identify problems, confirm functionality, and maintain code quality. Moreover, Jest is a popular choice because it does not need extensive configuration and you can start creating tests right away.
Also Read: Jest Framework Tutorial: How to use it?
Why use Jest to test React Apps?
There are many different solutions for testing React Apps to make sure the product is prepared for release to the market, but let’s look at some of the reasons why Jest is a superior option.
- Zero Configuration: Jest does not require an extensive configuration before you’re all set to start to test React applications. This is one of Jest’s most useful features, which makes it any developer’s first pick.
- Snapshot Testing: While developers make every effort to implement changes exactly as a designer intended, snapshot testing helps ensure this occurs. The visual representation of a code is recorded and then compared with a screenshot of a new scenario to validate whether there is a difference.
- React Integration: Jest is also mentioned in the official React documentation, emphasizing that it interacts easily with React development. It also works nicely with tools like the React Testing Library, which was created for user-centric testing of React components.
- Community Support: Since Jest is widely utilized in the React development community, there are a ton of resources available to help with any problems one may run into when using Jest to test React applications. The developers benefit from the abundance of instructions and solutions that are available online in numerous forums.
How to Test React Apps using Jest: Tutorial
Prerequisites
- You must have Node.Js installed on your system at least version 14 or higher.
- Install any IDE of your choice. In this example, we are using Visual Studio Code IDE.
- You must be familiar with the basic concepts of React.Js.
Setting Up and Installing Jest
Now, let’s set up our React project, and configure Jest to start snapshot testing of the React components.
Step 1: Install a React application
Create a new React application with the following command. Let’s name this project jest-tutorial.
npx create-react-app basic-app
Next, start the app.
npm start
Step 2: Configure Jest into your project
Install react-test-renderer with the following command to render the JavaScript objects without DOM.
npm install react-test-renderer
Step 3: Create a React application to perform testing
Let’s create a React application for which we will write multiple tests using Jest.
Write the following code inside the directory:
basic-app/src/components/HelloWorld.js.
import React from 'react' function HelloWorld() { return ( <div> <h1> Hello World </h1> </div> ) } export default HelloWorld
Also, update the basic-app/src/App.js file with the following script.
import React, { Component } from 'react'; import HelloWorld from './components/HelloWorld'; class App extends Component { render() { return ( <HelloWorld/> ); } } export default App;
After you have written the test file, follow the command to run the test on the root directory of your project ./basic-app.
npm test
1. Unit Testing of React Apps using Jest
Unit testing is a testing procedure through which an individual code of an application is tested in isolation to ensure that the code is working fine. The testing is done in isolation to avoid any code interaction with other components or dependencies.
import React from 'react'; import { render, screen } from '@testing-library/react'; import HelloWorld from '../components/HelloWorld'; test('renders the "Hello World" message', () => { render(<HelloWorld />); const helloWorldText = screen.getByText('Hello World'); expect(helloWorldText).toBeInTheDocument(); });
2. Snapshot Testing of React Apps using Jest
Snapshot testing is an automated testing procedure through which the current state of an application’s UI is captured and compared against the previously saved snapshot. It helps detect unexpected changes in the output and simplifies verifying code changes.
import React from 'react'; import renderer from 'react-test-renderer'; import HelloWorld from './HelloWorld'; it('performs snapshot testing', () => { const tree = renderer.create(<HelloWorld />).toJSON(); expect(tree).toMatchSnapshot(); });
When you run a test, it will search for all the test files stored in your project directory. To get rid of unnecessary failed tests, delete the App.test.js file. Since we’re not creating a test in that file, there’s no use in running a test on that file.
Best Practices for Testing React Apps with Jest
Before releasing the product to the market, testing verifies that it performs as planned. Since it is the product’s last stop before being distributed to real-world users, it is crucial to check that it is free of major issues because they might negatively impact the company’s reputation globally.
Here are certain best practices for testing React apps using Jest to provide optimum performance which will further improve the React Testing situation.
- Consistent Nomenclature of test files: If you’re consistently maintaining the naming convention of the test files, you’re also simultaneously increasing the maintainability of the entire project. Simply structuring the files correctly, and clearly describing the purpose of test files also encourages collaborativeness among the team members.
- Grouping tests logically: ‘Test Suite’ refers to the process of grouping numerous different tests into a single set. The primary advantages of creating test suites are that they structure your project which in turn organizes your test files, provides isolation for tests, allows selective tests, and more.
- Mock Dependencies: This allows the Jest users to isolate and test the React individual components well. This brings consistency in testing procedures by eliminating the need to rely upon external services and reduces flakiness in the test.
Also Read: Understanding Jest Mock Hook
Conclusion
The essential component of the software development sector is testing since it assures that users receive the best product, upholding the company’s reputation in the process. In this tutorial, we learned how to test using Jest in React applications.
Jest is a well-known JavaScript testing framework and is extensively used to test React applications due to several features, it does not require extensive configuration, strong community support, and seamless integration into React applications.
Moreover, we also came across a practical demonstration of how to implement Jest testing React applications. We saw two popular testing procedures, Unit Testing, and Snapshot testing. Snapshot testing is used to find any unintentional UI changes, whereas unit testing is used to test individual components of React applications by separating their interaction with other components or dependencies.
Follow-Up Read: How to Debug Jest Tests?