What Is Unit Testing In React

What is Unit Testing?

Unit testing is the testing process that tests the smallest parts of our application, like individual components or functions. This method checks whether our application parts are working or not.

In React, the small parts of an app are called “units”. It can be buttons, hooks, or even calculation functions.

This method tests all the parts in isolation mode, without depending on the entire application.

We can use two React libraries to write unit tests in our application:

  • Jest (Testing Framework)
  • React Testing Library
  • Enzyme (Deprecated)

Jest is a powerful testing framework that helps you to write and run test cases and allows you to compare expected results with the actual results.

React Testing Library does not check the internal code and class names of a component; It checks how a real person interacts with your UI. It is checking the:

  • Clicking on buttons
  • Typing into input boxes
  • Screen text reading.
  • dropdown selection by users

Enzyme (Deprecated) was popular in the past, but the Enzyme library has fallen out of use due to limited support with React’s latest versions.

Note: Install both Jest and React Testing Library for proper unit testing in React.

How To Install Unit Testing Libraries In React

First, we will install and set up Jest and React Testing Libraries in our project.

Run this command in your terminal:

npm install --save-dev jest @testing-library/react @testing-library/jest-dom @babel/preset-env @babel/preset-react babel-jest identity-obj-proxy

These command include:

  • jest: Testing framework
  • @testing-library/react: For testing React components
  • @testing-library/jest-dom: For helpful matchers like toBeInTheDocument()
  • babel-jest: Transpires JSX/ES6 for Jest
  • @babel/preset-env and @babel/preset-react: To configure Babel for React
  • identity-obj-proxy: Helps mock CSS modules in tests

Create Babel Config (for JSX support)

Now, create a babel.config.js file in the root:

// babel.config.js
module.exports = {
presets: ['@babel/preset-env', '@babel/preset-react'],
};

Create Jest Config

Create a jest.config.js file in your root directory:

// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
moduleNameMapper: {
'\\.(css|scss)$': 'identity-obj-proxy'
},
setupFilesAfterEnv: ['<rootDir>/setupTests.js'],
transform: {
'^.+\\.(js|jsx)$': 'babel-jest'
},
moduleFileExtensions: ['js', 'jsx'],
};

Create setupTests.js (For Jest DOM Matchers)

Create a setupTests.js file in the root:

// setupTests.js
import '@testing-library/jest-dom';

This makes matchers like toBeInTheDocument() available globally.

Add a Test Script in package.json

Add this command in your package.json file:

"scripts": {
"test": "jest"
}

Write a Sample Test

Create a __tests__ or tests folder, and add a App.test.js file:

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

test('renders welcome message', () => {
render(<App />);
const heading = screen.getByText(/welcome/i);
expect(heading).toBeInTheDocument();
});

Run Your Tests In The Terminal

npm run test

Real Life Example of Unit Testing

You have a simple React component:

// Button.js
import React from 'react';

function Button({ label, onClick }) {
return <button onClick={onClick}>{label}</button>;
}

export default Button;

This button receives:

  • A label (like “Click Me”)
  • An onClick function (what to do when clicked)

Write a Testing Code

// Button.test.js
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';

test('renders the button with given label and clicks it', () => {
const mockClick = jest.fn(); // fake function to check if it was called

render(<Button label="Click Me" onClick={mockClick} />);

const buttonElement = screen.getByText("Click Me");
expect(buttonElement).toBeInTheDocument(); // check if button shows up

fireEvent.click(buttonElement); // simulate button click
expect(mockClick).toHaveBeenCalledTimes(1); // check if click worked
});

Code Explanation

Code LinesExplanation
jest.fn()Creates a fake function to test clicks.
render(…)Loads the Button component for testing.
screen.getByText(…)Finds the button by its text.
expect(…).toBeInTheDocument()Confirms the button is visible.
fireEvent.click(…)Simulates the user clicking the button.
expect(…).toHaveBeenCalledTimes(1)Checks if the button was clicked exactly once.

How to Run This Test?

  1. Make sure your test file is named is Button.test.js
  2. Run this command in your terminal:
npm test

This will do:

  • Find the test files
  • Run them
  • It will showing you if anything fails.

What Is Snapshot Testing In React

A snapshot in React testing is a text-based copy of the rendered output of your component. It looks like an HTML code structure.

What Happens During Snapshot Testing?

  • When the first time we run the test, Jest creates a snapshot file of how our component looks.
  • The second time we will run the test, so Jest compares the new output of the component with the previous snapshot.
  • The test will pass if the both output matches.
  • The test fails if the output changes due to a bug or mistake.

Example of a Snapshot Testing

If the Greeting component renders this structure:

<h1>Hello John</h1>

Then, the snapshot testing will generate this file:

exports[`Greeting component renders correctly 1`] = `
<h1>
Hello John
</h1>
`;

This file is auto-saved by Jest inside a __snapshots__ folder.

What Is Event Testing In React?

Event testing is checking whether the app responds to user actions correctly or not.

The goal of event testing is to make sure that the right functions are triggered and the UI updates as expected when users perform these actions

Example of Event Testing

Consider a Counter component that increments a count each time a button is clicked:

// Counter.js
import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

const increment = () => setCount(count + 1);

return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}

export default Counter;

This is a test code of Event testing:

// Counter.test.js
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';

test('increments count when button is clicked', () => {
render(<Counter />);
const button = screen.getByText('Increment');
fireEvent.click(button);
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});

Explanation of This Code:

  • fireEvent.click: Simulates a click event on the button.
  • expect(screen.getByText(‘Count: 1’)): Checks if the count has incremented to 1 after the button click.

Leave a Comment