How To Mock A React Component In Jest (2025)

Testing is one of the most important aspects to React development. Without tests, you can’t have confidence that your code will work as it’s supposed to do. For testing purposes, it can be relevant to mock a React component. This article will show you how to mock your React components in different scenarios using Jest. Using this information, you’ll know how to mock default exported components, named exported components, components that come from ES6 modules and include the props with them.

Default Export

To mock a React component, the most straightforward approach is to use the jest.mock function. You mock the file that exports the component and replace it with a custom implementation. Since a component is basically a function, the mock should also return a function. The implementation would look as follows.

jest.mock("./AwesomeComponent", () => () => { const MockName = "default-awesome-component-mock"; return <MockName />;});// Tests

This assumes that the component you’re mocking is the default export of the file. On top of that, it creates a custom name for the component in the test environment. This will simplify the resulting DOM structure, which can be useful e.g. snapshot tests.

Named Export

As mentioned, the previous implementation was for a component that is the default export of a file. But how do you mock a React component that is the named export of a file? For that, the implementation should mock the entire export of the file, instead of only the default export. That would look as follows.

jest.mock("./AwesomeComponent", () => ({ AwesomeComponent: () => { const MockName = "named-awesome-component-mock"; return <MockName />; },}));

Instead of returning a function, the mock returns an object that replaces the export of the file. Inside the object, we state the property that needs to be replaced. Then, we can specify the replacement code for it, which is the same as the previous function that we used.

If you’re dealing with ES6 modules, you’ll need some additional configurations to make it work. Specifically, you’ll need the add the __esModule property to the exported object and set it to true. This signals that you’re dealing with ES6 modules and makes everything work properly. The implementation would look as follows.

jest.mock("./AwesomeComponent", () => ({__esModule: true, AwesomeComponent: () => { const MockName = "named-awesome-component-mock"; return <MockName />; },}));

Including Props

We now know how to create a mock for a component that is either the default or named export of a file. But the problem is that the current mock overwrites everything from the component, including the DOM structure and props. In certain scenarios, we want to mock everything related to a component but still keep the props for testing purposes.

jest.mock("./AwesomeComponent", () => ({ AwesomeComponent: (props) => { const MockName = "named-awesome-component-mock"; return <MockName {...props} />; },}));

Luckily, adding the props back to our mock implementation doesn’t require a lot of effort. Similarly to how props are defined for a usual React component, we need to capture the function parameters and pass them to the rendered elements. Doing so will include the passed props to the mocked component and allow us to use them in our tests.

Final Thoughts

For testing purposes, it can be relevant to mock a certain React component. This article showed you how to mock your React components in different scenarios. This covers default exported components, named exported components, components that come from ES6 modules, and including the props with them.

How To Mock A React Component In Jest (2025)

FAQs

How to mock React component function in Jest? ›

To mock a module with both, you can use the default key, but you also must specify that it's an ES6 module with a special __esModule key: export { A }; export default B; jest. mock("../src/Icon", () => { return { __esModule: true, A: true, default: () => { return <div></div>; }, }; });

How to mock React state in Jest? ›

The basic syntax and usage of mocking hooks in Jest involves using the jest. mock() function to mock the behavior of the hook you want to replace. We have a React component that uses the 'useEffect' hook to fetch data from an API. We want to test the component's behavior without making actual network requests.

What is mocking in Jest? ›

In Jest, mocking modules entails replacing a module's actual implementation with a phoney one. This is frequently done to separate a module from its dependencies or to prevent calling outside resources while testing.

How to mock a third party React component using Jest? ›

To do so, make a new directory called '__mocks__' next to the component you want to mock. Remove the factory argument from your call to jest. mock, and jest will automatically locate manual mocks and use them in your test.

What is mock response of function in Jest? ›

Mock functions are also known as "spies", because they let you spy on the behavior of a function that is called indirectly by some other code, rather than only testing the output. You can create a mock function with jest. fn() . If no implementation is given, the mock function will return undefined when invoked.

Which is better, cypress or Jest? ›

Cypress is a robust end-to-end testing framework designed for testing the entire application from the user's perspective. Jest is primarily a unit testing framework, although it supports integration and end-to-end testing. In some cases, a combination of both Cypress and Jest might be beneficial.

What is auto mocking in Jest? ›

Automatic mock​

Calling jest. mock('./sound-player') returns a useful "automatic mock" you can use to spy on calls to the class constructor and all of its methods. It replaces the ES6 class with a mock constructor, and replaces all of its methods with mock functions that always return undefined .

Can we mock useState in Jest? ›

To use jest to mock useState, we'll need to actually use useState from React. The jest. requireActual() function allows us to return the actual React useState module instead of mocking it out.

How do I view React components? ›

Open the console by either right-clicking and inspecting an element or by opening the toolbar by clicking View > Developer > JavaScript console. The Components tab will show the current React component tree, along with any props, state, or context.

How to run a test for a specific component in React? ›

React Testing Components with Jest
  1. Step 1: Install Jest. npm install --save-dev jest.
  2. Step 2: Write a Test. Create a . test. ...
  3. Step 3: Execute the Test. To execute the test, run the following command in the terminal. In this test case, we tested if our application contains the 'helloworld' text.
Apr 24, 2023

Is Vitest better than Jest? ›

Conclusion. With its simplicity and React testing library integration, Jest is ideal for projects that require a robust and more stable ecosystem. On the other hand, Vitest's flexibility and language-agnostic approach make it an ideal choice for new and modern projects.

Is Jest mocking or spying? ›

The main difference in spying and mocking is, when you are spying you are not undermining the entire function implementation, rather you are just targeting a few lines of code which is making it untestable. But in mocking, you are undermining the entire function implementation and you are just returning the value.

Is mocking good or bad? ›

Mocks are not an evil thing. They are great at some things and they are bad if you don't use them properly. If you need to mock something don't feel you're doing it wrong but, also, don't fall back into mocking everything that the code you are testing needs, think about whether that's the right choice or not.

What is an example of mocking? ›

Meaning of mock in English. to laugh at someone, often by copying them in a funny but unkind way: They were mocking him because he kept falling off his bike. She made fun of him by mocking his limp.

How to mock a function import in Jest? ›

No matter the reason, this article will go over how to mock the return value of an imported function in Jest. To mock the return value of an imported function in Jest, you have to either call mockReturnValue or mockImplementation on a Jest mock function and then specify the return value.

How to mock a function inside a class Jest? ›

Calling jest.mock() with the module factory parameter

A module factory is a function that returns the mock. In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF).

How to test function inside class component Jest? ›

In Jest, jest. spyOn() is a powerful tool that allows us to monitor the calls to a specific function, checking how many times it was called, what arguments it was called with, and more. But for jest. spyOn() to work, the function in question needs to be accessible in the module's exports.

How to mock a function in React testing library? ›

mock() method may be used. It accepts a path to the file where the module to be mocked is defined and replaces the actual module with the version defined in the __mocks__/ folder. The file to be mocked must be imported before it can be mocked with jest. mock() .

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Geoffrey Lueilwitz

Last Updated:

Views: 6430

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Geoffrey Lueilwitz

Birthday: 1997-03-23

Address: 74183 Thomas Course, Port Micheal, OK 55446-1529

Phone: +13408645881558

Job: Global Representative

Hobby: Sailing, Vehicle restoration, Rowing, Ghost hunting, Scrapbooking, Rugby, Board sports

Introduction: My name is Geoffrey Lueilwitz, I am a zealous, encouraging, sparkling, enchanting, graceful, faithful, nice person who loves writing and wants to share my knowledge and understanding with you.