, ,

Testing React Components with Jest: A Step-by-Step Tutorial

Posted by


Testing React Components with Jest: A Step-by-Step Tutorial

If you are building a React application, testing your components is an essential part of the development process. One popular testing framework for React is Jest, which provides a simple and robust way to test your components. In this tutorial, we will walk through the steps of testing React components with Jest, from setting up your testing environment to writing and running your tests.

Setting Up Your Testing Environment

Before we can start testing our React components with Jest, we need to set up our testing environment. If you haven’t already, make sure to install Node.js and npm (the Node.js package manager) on your machine. Once Node.js and npm are installed, you can create a new React project using Create React App, which is a convenient tool for setting up a new React project with a pre-configured build system.

To create a new React project with Create React App, open your terminal and run the following command:

“`html
npx create-react-app my-app
“`

This will create a new directory called my-app and install all the necessary dependencies for a new React project. Once the project is created, navigate to the my-app directory and install Jest and the react-testing-library, which is a popular testing utility for React components.

“`html
cd my-app
npm install –save-dev jest @testing-library/react @testing-library/jest-dom
“`

Writing Your First Test

With the testing environment set up, we can now write our first test for a simple React component. Create a new file called Button.js in the src directory of your project and add the following code:

“`html
// Button.js

import React from ‘react’;

const Button = ({ onClick, children }) => {
return (

);
}

export default Button;
“`

Next, create a new file called Button.test.js in the same directory and add the following code to write a test for the Button component:

“`html
// Button.test.js

import React from ‘react’;
import { render, fireEvent } from ‘@testing-library/react’;
import Button from ‘./Button’;

test(‘renders a button with the correct text’, () => {
const handleClick = jest.fn();
const { getByText } = render(

);

const button = getByText(‘Click me’);
expect(button).toBeInTheDocument();

fireEvent.click(button);
expect(handleClick).toHaveBeenCalledTimes(1);
});
“`

In this test, we use the render and fireEvent functions from the @testing-library/react package to render the Button component and simulate a click event on the button. We also use the jest.fn function to create a mock function for the onClick event handler. Finally, we use expect assertions to verify that the button renders with the correct text and that the onClick event handler is called when the button is clicked.

Running Your Tests

Now that we have written our first test, we can run the test using Jest. Open your terminal and run the following command to run the tests for your React project:

“`html
npm test
“`

This will run all the test files in your project and display the results in your terminal. If everything is set up correctly, you should see the results of your test, with a summary of how many tests passed and how many failed.

Testing React Hooks

In addition to testing React components, Jest can also be used to test React hooks, which are a powerful feature of React for handling state and side effects in functional components. Let’s look at an example of how to test a simple custom hook using Jest.

Create a new file called useCounter.js in the src directory of your project and add the following code to define a custom hook that counts the number of times a button is clicked:

“`html
// useCounter.js

import { useState } from ‘react’;

const useCounter = () => {
const [count, setCount] = useState(0);

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

return { count, increment };
}

export default useCounter;
“`

Next, create a new file called useCounter.test.js in the same directory and add the following code to write a test for the useCounter hook:

“`html
// useCounter.test.js

import { renderHook, act } from ‘@testing-library/react-hooks’;
import useCounter from ‘./useCounter’;

test(‘increments the count when the increment function is called’, () => {
const { result } = renderHook(() => useCounter());

expect(result.current.count).toBe(0);
act(() => {
result.current.increment();
});
expect(result.current.count).toBe(1);
});
“`

In this test, we use the renderHook and act functions from the @testing-library/react-hooks package to render the useCounter hook and simulate a call to the increment function. We then use expect assertions to verify that the count is incremented when the increment function is called.

Mocking Dependencies

When testing React components and hooks, you may need to mock external dependencies, such as APIs or libraries, in order to isolate the code being tested and prevent side effects. Jest provides a built-in mocking system that allows you to replace modules and functions with mock versions for the purpose of testing.

To demonstrate how to mock dependencies in Jest, let’s look at an example of mocking a fetch request in a React component. Add the following code to a new file called UserList.js in the src directory of your project:

“`html
// UserList.js

import React, { useState, useEffect } from ‘react’;

const UserList = () => {
const [users, setUsers] = useState([]);

useEffect(() => {
fetch(‘https://jsonplaceholder.typicode.com/users’)
.then(response => response.json())
.then(data => setUsers(data));
}, []);

return (

    {users.map(user => (

  • {user.name}
  • ))}

);
}

export default UserList;
“`

To test the UserList component, we can use Jest’s mocking system to mock the fetch function and provide a mock response for the fetch request. Create a new file called UserList.test.js in the same directory and add the following code to write a test for the UserList component:

“`html
// UserList.test.js

import React from ‘react’;
import { render, act } from ‘@testing-library/react’;
import UserList from ‘./UserList’;

beforeAll(() => {
global.fetch = jest.fn(() =>
Promise.resolve({
json: () =>
Promise.resolve([
{ id: 1, name: ‘John Doe’ },
{ id: 2, name: ‘Jane Doe’ }
])
})
);
});

test(‘renders a list of users’, async () => {
await act(async () => {
const { getByText } = render();
expect(getByText(‘John Doe’)).toBeInTheDocument();
expect(getByText(‘Jane Doe’)).toBeInTheDocument();
});
});
“`

In this test, we use the beforeAll lifecycle hook to replace the global fetch function with a mock function that returns a Promise.resolve with a mock response for the fetch request. We then use the render function from @testing-library/react to render the UserList component and use expect assertions to verify that the list of users is rendered correctly.

Conclusion

In this tutorial, we have learned how to set up your testing environment for testing React components with Jest, write and run tests for React components and hooks, and mock external dependencies for testing purposes. With Jest, you can ensure the reliability and correctness of your React code by testing your components in a systematic and repeatable manner. By following the step-by-step instructions provided in this tutorial, you can start testing your React components with Jest and improve the quality of your React applications. Happy testing!