Use Jest to unit test your React project

Tiempo de lectura: 2 minutos

Unit testing is an essential part of software development that ensures different parts of your application work correctly. In this tutorial, we will learn how to write unit tests for a React component using Jest and @testing-library/react.

Prerequisites

Make sure you have Node.js and npm installed on your machine before starting. You can verify this by running the following commands in your terminal:

node --version
npm --version

If you don’t have them installed, you can download and install Node.js from https://nodejs.org/.

Project Setup

  1. Create a new React project using create-react-app:
npx create-react-app react-testing-tutorial
cd react-testing-tutorial
  1. Install the necessary dependencies for unit testing:
npm install --save-dev jest @testing-library/react @testing-library/jest-dom

Component Structure

Let’s assume we have a simple button component in Button.js:

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

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

export default Button;

Writing Unit Tests

  1. Create a test file for the Button component. Let’s call it Button.test.js:
// src/Button.test.js
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Button from './Button';

test('renders button with correct label', () => {
  const label = 'Click me';
  const { getByText } = render(<Button label={label} />);
  const button = getByText(label);
  expect(button).toBeInTheDocument();
});

test('calls onClick prop when button is clicked', () => {
  const onClickMock = jest.fn();
  const { getByText } = render(<Button label="Click me" onClick={onClickMock} />);
  const button = getByText('Click me');
  fireEvent.click(button);
  expect(onClickMock).toHaveBeenCalledTimes(1);
});

In this example:

  1. The first test case verifies that the button is rendered correctly with the provided label.
  2. The second test case verifies that the onClick function is called correctly when the button is clicked.

Running the Tests

Make sure you have the following script in your package.json:

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

Then, run your tests with:

npm test

Conclusions

Congratulations! You now have basic unit tests for your React component. This is just a simple example, but as your application grows, you could add more tests to ensure robust and reliable code.

Leave a Comment