ReactJS: Learn how to use jest.mock to mock dependencies in your ReactJS unit tests

ReactJS: Learn how to use jest.mock to mock dependencies in your ReactJS unit tests

Introduction

Mocking dependencies is a common practice in unit testing. It allows us to isolate our component under test and simulate different scenarios without relying on the actual behavior of the dependencies. In ReactJS, we can use jest.mock to easily mock dependencies in our unit tests.

In this tutorial, we will walk through an example that demonstrates how to use jest.mock to mock dependencies in your ReactJS unit tests. We will create a simple component that depends on an external module and write tests that verify its behavior when the dependency is mocked.

Prerequisites

To follow along with this tutorial, make sure you have the following installed:

  • Node.js (v14 or above)
  • npm or yarn (any version)
  • Jest (v26 or above)
  • React (v16 or above)

Setting up the project

Let’s start by setting up a new React project. Open your terminal and run the following command to create a new React project:

npx create-react-app react-mock-dependencies
cd react-mock-dependencies

Next, install Jest as a dev dependency by running the following command:

npm install --save-dev jest

Once Jest is installed, we are ready to start writing our tests.

Creating the component and its dependency

In our example, we will create a simple counter component that increments a value by 1 when a button is clicked. The component relies on an external module called api to perform the increment operation.

Create a new file Counter.js in the src directory and add the following code:

import React, { useState } from 'react';
import { incrementValue } from './api';

export default function Counter() {
  const [value, setValue] = useState(0);

  const handleClick = () => {
    const newValue = incrementValue(value);
    setValue(newValue);
  };

  return (
    <div>
      <p>Value: {value}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

Next, create a new file api.js in the src directory and add the following code:

export function incrementValue(value) {
  return value + 1;
}

Writing the unit tests

Now let’s write the unit tests for our Counter component. Create a new file Counter.test.js in the src directory and add the following code:

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Counter from './Counter';
import { incrementValue } from './api';

// Mocking the dependency
jest.mock('./api');

// Mocking the incrementValue function
incrementValue.mockReturnValue(2);

test('renders the counter value', () => {
  const { getByText } = render(<Counter />);
  expect(getByText('Value: 0')).toBeInTheDocument();
});

test('increments the counter value when the button is clicked', () => {
  const { getByText } = render(<Counter />);
  const button = getByText('Increment');

  fireEvent.click(button);

  expect(incrementValue).toHaveBeenCalledTimes(1);
  expect(button).toHaveTextContent('Increment');
  expect(getByText('Value: 2')).toBeInTheDocument();
});

In the above code, we import the necessary functions from the testing-library/react package, including the render and fireEvent functions for rendering and interacting with the component. We also import the Counter component and the incrementValue function from the api.js file.

Next, we use jest.mock to mock the api.js module. This ensures that when Counter.js imports and uses the incrementValue function, it actually uses the mocked version.

We then use incrementValue.mockReturnValue(2) to specify the return value of the mocked incrementValue function.

Finally, we write two tests: one to verify that the initial counter value is rendered correctly, and another to verify that the counter value is incremented when the button is clicked. We use fireEvent.click to simulate a button click and assert various conditions using Jest’s expect assertions.

Running the tests

To run the tests, open your terminal and run the following command from the project root directory:

npm test

Jest will execute the tests and show the test results in the terminal.

Conclusion

In this tutorial, you have learned how to use jest.mock to mock dependencies in your ReactJS unit tests. Mocking dependencies is important because it allows you to test components in isolation without relying on external modules or APIs. By using jest.mock, you can easily simulate different scenarios and verify the behavior of your components.

Remember, unit testing is an essential part of the development process, and using tools like Jest can greatly simplify the testing process for your ReactJS applications.

I hope you found this tutorial helpful. Happy coding!