top of page
90s theme grid background
  • Writer's pictureGunashree RS

Guide to Jest Testing: Comprehensive Tutorial for React

Updated: Aug 9

Introduction

Testing is an essential part of software development, ensuring that applications are reliable, maintainable, and perform as expected. For React applications, Jest is a popular testing framework due to its simplicity and powerful features. This guide provides an in-depth look at Jest testing, including setting up a testing environment, writing tests, mocking data, checking code coverage, and best practices.


What is Unit Testing in React?

Unit testing is a type of software testing where individual units or components of the software are tested in isolation. In the context of React applications, a unit could be a React component, a helper function, or any other JavaScript module. The primary goal is to verify that each unit performs as designed.


Unit testing

Why Unit Testing in React is Important?

Unit testing in React is crucial for several reasons:

  • Maintains Code Quality: Ensures that components behave as expected, reducing bugs and errors.

  • Eases Debugging: Simplifies the process of identifying and fixing issues.

  • Acts as Documentation: Provides a detailed description of the system’s design and functionality.

  • Facilitates Refactoring: Allows developers to confidently make changes and improvements to the codebase.


What to Test in Unit Testing for React Apps?

In a React application, various aspects can be tested, including:

  • Component Rendering: Ensure that components render correctly under different conditions.

  • State and Props: Test state changes and the props being received.

  • Event Handling: Check if events like clicks and input changes are handled correctly.

  • Lifecycle Methods: Validate that lifecycle methods work as expected.



Prerequisite (Project Setup) of React Unit Testing in JEST

Before starting with testing, setting up the project environment is essential. Here are the steps:


1. Install Node.js and npm

Node.js is required to run React applications, and npm (Node Package Manager) is used to manage packages. Both can be downloaded and installed from the official Node.js website.


2. Create a New React Application

Create a new React application using the create-vite command. Run the following commands in the terminal:

bash

npm init vite@latest jest-react-app --template react

This command creates a new directory named jest-react-app with a new React application.


3. Navigate to the Project Directory

Change the current directory to the newly created React application directory:

bash

cd jest-react-app

4. Install Jest and jest-axe

Install Jest and jest-axe as development dependencies:

bash

npm install --save-dev jest jest-axe

5. Verify Installation

Verify the installation of Jest by running:

bash

npx jest --version

This command should print the installed version of Jest.


6. Install Other Required Dependencies

Install additional dependencies needed for testing:

bash

npm install axios
npm install --save-dev @babel/preset-react @babel/preset-env @testing-library/jest-dom jest-environment-jsdom

7. Setup Running Environment


a) Create babel.config.js

Create a babel.config.js file at the root of the project with the following code:

javascript

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
     },
    ],
    '@babel/preset-react',
  ],
  plugins: [],
};

b) Create jest.config.js

Create a jest.config.js file at the root of the project:

javascript

module.exports = {
  testEnvironment: "jsdom",
  transform: {
    '^.+\\.(js|jsx|ts|tsx)$': 'babel-jest',
  },
  setupFilesAfterEnv: ['@testing-library/jest-dom'],
};

c) Update package.json

Add the test command to the scripts section of the package.json file:

json

"scripts": {
  "test": "jest",
  // other scripts...
}

How to Perform Unit Testing of React Apps using JEST?

Unit testing involves creating test cases for components and running them using Jest. Here are the high-level steps:


Identify What to Test

Determine the functionality that needs to be tested. This could be a function, a component, or an entire feature.


Write the Test

Write a test that checks if the identified functionality works as expected. This involves setting up the necessary environment, executing the functionality, and checking the result.


Run the Test

Use Jest to run the test and check if it passes or fails.


Analyze the Result

If the test fails, analyze why it failed and fix the issue. If it passes, move on to the next functionality to test.


Example Test Case

Here’s an example of a simple test case using Jest and the React Testing Library:

javascript

import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});

This test checks if the App component renders a link with the text 'learn to react'.


Mocking Data in React Unit Testing with Jest

Mocking in unit testing involves creating stand-ins or substitutes for the real parts of your code. Jest provides built-in features for mocking functions, modules, and components, making tests more reliable and easier to manage.


Example of Mocking Data

Consider a User component that fetches user data from an API when it’s mounted:

javascript

// User.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';

const User = () => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const response = await axios.get('https://api.example.com/user');
      setUser(response.data);
    };
    fetchData();
  }, []);

  if (!user) {
    return 'Loading...';
  }

  return <div>{user.name}</div>;
};

export default User;

Mocking Axios in Jest

Here’s how to mock the axios module to control the data returned by the API:

javascript

// User.test.js
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import axios from 'axios';
import User from './User';

// Mocking axios module
jest.mock('axios');

test('fetches and displays user data', async () => {
  // Create a mock response
  const mockResponse = { data: { name: 'John Doe' } };
  axios.get.mockResolvedValue(mockResponse);

  // Render the User component
  render(<User />);

  // Check if the mocked response is used in the component
  const userNameElement = await waitFor(() => screen.getByText(/John Doe/i));
  expect(userNameElement).toBeInTheDocument();
});

In this test, the axios module is mocked using jest.mock(), and a mock response is created. The User component is then rendered, and it is checked if the user name from the mock response is present in the document.



Code Coverage During React Unit Testing Using Jest

Code coverage measures the extent to which the code is covered by tests. Jest can generate a code coverage report by adding the --coverage flag to the test command.


Updating the Test Command

Update the test command in the package.json file:

json

"scripts": {
  "test": "jest --coverage",\
  // other scripts...
}

Running the Tests

Run the tests with the updated command:

bash

npm run test

Checking the Coverage Report

After running the tests, Jest will output a code coverage report in the terminal, showing the percentage of the code covered by tests.



Performance Optimization in React Unit Testing

Performance optimization in testing refers to improving the speed and efficiency of your test suite. Here are some strategies:


Avoid Unnecessary Rendering

Ensure that only the necessary components are rendered during tests.


Use Shallow Rendering

Shallow rendering renders a component "one level deep" and prevents unnecessary rendering of child components.


Mock Heavy Dependencies

Mock dependencies that are heavy or slow, such as network requests, using Jest’s mocking features.


Run Tests in Parallel

Jest runs tests in parallel by default, speeding up the test suite. Ensure that tests are independent so they can run in any order.


Limit Snapshot Tests

While snapshot tests are useful, they can slow down the test suite if overused. Prefer explicit assertions whenever possible.



Accessibility Testing in React Using Jest Axe

Accessibility testing ensures that your application is usable by everyone, including those with disabilities. Jest Axe integrates with Jest to run accessibility checks on React components using the Axe accessibility testing engine.


Example of Accessibility Testing

javascript

// Input.js
import React from 'react';
import PropTypes from 'prop-types';

const Input = ({ label, ...props }) => {
 return (
<div>
      <label htmlFor="input-field">{label}</label>
      <input id="input-field" {...props} />
    </div>
  );
};
Input.propTypes = {
  label: PropTypes.string.isRequired,
};
export default Input;
// Input.test.js
import React from 'react';
import { render } from '@testing-library/react';
import { axe, toHaveNoViolations } from 'jest-axe';
import Input from './Input';
// Add a Jest matcher to check for accessibility violations
expect.extend(toHaveNoViolations);
test('Input component should have no accessibility violations', async () => {
  const { container } = render(<Input label="Test input" />);
  const results = await axe(container);
  // Assert that there are no accessibility violations
  expect(results).toHaveNoViolations();
});

In this test, the Input component is rendered with a label. The axe function from jest-axe is used to run accessibility checks on the rendered component, and toHaveNoViolations asserts that there are no accessibility violations.



Best Practices for Testing React Apps with JEST

  • Write Clear, Descriptive Test Cases: Ensure that test cases are easy to understand and maintain.

  • Test Component Behavior, Not Implementation Details: Focus on what the component does, not how it does it.

  • Keep Tests Isolated: Ensure that tests are independent and do not rely on each other.

  • Regularly Update Tests: Keep tests up to date as component functionality changes.

  • Use Mocking Wisely: Mock dependencies and modules to isolate tests and improve performance.



Conclusion

Unit testing is a vital part of software development, ensuring that code works as expected and maintaining high-quality standards. Jest, combined with the React Testing Library, provides a comprehensive solution for writing robust, reliable tests for React applications. By following best practices and utilizing tools like Jest Axe for accessibility, developers can build applications that are not only functional but also accessible and performant.



Key Takeaways

  • Jest Testing: Comprehensive testing framework for JavaScript and React applications.

  • Unit Testing Importance: Maintains code quality, facilitates debugging, and serves as documentation.

  • Mocking Data: Use Jest's mocking features for reliable and manageable tests.

  • Code Coverage: Measure the extent of code covered by tests using Jest.

  • Performance Optimization: Avoid unnecessary rendering, use shallow rendering, mock dependencies, and run tests in parallel.

  • Accessibility Testing: Ensure your application is accessible using Jest Axe.

  • Best Practices: Write clear test cases, keep tests isolated, regularly update tests, and use mocking wisely.



FAQs


What is Jest testing?

Jest is a JavaScript testing framework designed to ensure the correctness of any JavaScript codebase. It is often used for testing React applications due to its simplicity and powerful features.


Why is unit testing important in React?

Unit testing ensures that individual components work as expected helps maintain code quality, facilitates debugging, and serves as documentation for the system's design and functionality.


How do you mock data in Jest?

Jest provides built-in features for mocking functions, modules, and components. This is useful for testing parts of your code that rely on external data or dependencies.


What is code coverage in Jest?

Code coverage measures the extent to which your code is covered by tests. Jest can generate a code coverage report, showing the percentage of code tested.


How can you optimize performance in Jest tests?

Performance can be optimized by avoiding unnecessary rendering, using shallow rendering, mocking heavy dependencies, running tests in parallel, and limiting the number of snapshot tests.


What is accessibility testing in Jest?

Accessibility testing ensures that your application is usable by everyone, including those with disabilities. Jest Axe can be used to run accessibility checks on React components.


What are the best practices for Jest testing in React?

Best practices include writing clear test cases, testing component behavior, keeping tests isolated, regularly updating tests, and using mocking wisely.


How do you set up Jest for a new React project?

Setting up Jest involves installing Jest and related dependencies, configuring Babel and Jest, and updating the package.json file with the necessary scripts.


Article Sources

Opmerkingen


bottom of page