How to Mock a React Component in Jest

When I build a sales activity dashboard, I often start with a parent page that pulls together several child components: a summary card, an activity list, a filter bar, and a loading panel. Testing the whole screen at once sounds useful, but it can make one small parent-component test slow and hard to understand.

That is where you mock a React component in Jest. A mock replaces a real child component with a simple test version, so your test can focus on the parent component’s behavior instead of the child’s internal logic.

This practical React tutorial shows how to mock components with Jest, verify props, handle default and named exports, and avoid common testing mistakes.

Why Mock a React Component in Jest?

A component is a reusable piece of UI code that returns content for the browser to render. In React, a parent component often imports and renders child components through JSX, which is the HTML-like syntax used inside JavaScript files.

For example, a SalesDashboard component may render a RecentActivityList component. The dashboard controls which activities it sends, while the child component controls the detailed list markup.

When you mock a React component in Jest, you replace the real child component during the test. This gives you a smaller and more focused test.

Mocking helps when a child component:

  • Fetches data from an API.
  • Contains complicated logic that has its own tests.
  • Uses a third-party dependency.
  • Includes animations, charts, routing, or context providers.
  • Produces markup that does not matter to the current parent test.

This is especially useful in dashboards, admin portals, local frontend applications, and API-driven interfaces. If you are still setting up your first project, review this guide on setting up a ReactJS environment.

How to Mock a React Component in Jest

The most common approach uses jest.mock(). Jest intercepts the imported module and supplies the replacement component that you define.

Let’s use a sales activity dashboard throughout this guide. The dashboard displays recent activity from sales representatives such as Emily Carter, Michael Brooks, and Olivia Davis.

Create the Child Component

First, create the real child component. This component accepts an activities prop. Props are values that a parent component passes into a child component.

// RecentActivityList.jsx
function RecentActivityList({ activities }) {
return (
<section>
<h2>Recent Sales Activity</h2>

<ul>
{activities.map((activity) => (
<li key={activity.id}>
{activity.salesRep} updated {activity.customer}
</li>
))}
</ul>
</section>
);
}

export default RecentActivityList;

This code receives an array through the activities prop and uses map() to render one list item for each activity. The key uses a stable activity ID, which helps React track each item correctly while rendering lists.

Sample output:

Recent Sales Activity

Emily Carter updated Northwind Traders
Michael Brooks updated Blue Ridge Supply
Olivia Davis updated Greenfield Market

You can see the output in the screenshot below.

Mock a React Component in Jest

If you need help understanding how parent components pass values down, see this practical guide on props in React JS.

Create the Parent Component

Now create the parent component that imports the real child component.

// SalesDashboard.jsx
import { useState } from "react";
import RecentActivityList from "./RecentActivityList";

function SalesDashboard() {
const [activities, setActivities] = useState([
{
id: 101,
salesRep: "Emily Carter",
customer: "Northwind Traders",
},
{
id: 102,
salesRep: "Michael Brooks",
customer: "Blue Ridge Supply",
},
{
id: 103,
salesRep: "Olivia Davis",
customer: "Greenfield Market",
},
]);

function addActivity() {
const newActivity = {
id: 104,
salesRep: "Daniel Moore",
customer: "Summit Retail",
};

setActivities((currentActivities) => [
...currentActivities,
newActivity,
]);
}

return (
<main>
<h1>Sales Activity Dashboard</h1>

<button onClick={addActivity}>Add Activity</button>

<RecentActivityList activities={activities} />
</main>
);
}

export default SalesDashboard;

This component uses the useState hook. A hook is a React function that lets a functional component use React features. Here, state stores the sales activity array between renders.

The addActivity function is an event handler. An event handler is a function that runs after a user action, such as clicking a button. Notice that the code creates a new array with the spread operator instead of changing the existing array. That is an immutable update, which means you create new data rather than mutate existing data.

Sample output before clicking the button:

Sales Activity Dashboard

[Add Activity]

Recent Sales Activity
Emily Carter updated Northwind Traders
Michael Brooks updated Blue Ridge Supply
Olivia Davis updated Greenfield Market

You can see the output in the screenshot below.

How to Mock a React Component in Jest

Sample output after clicking “Add Activity”:

Sales Activity Dashboard

[Add Activity]

Recent Sales Activity
Emily Carter updated Northwind Traders
Michael Brooks updated Blue Ridge Supply
Olivia Davis updated Greenfield Market
Daniel Moore updated Summit Retail

For more hands-on examples of user actions in a React component, read this guide on handling events in React JS.

Mock the Child Component in the Test

Next, write a test that mocks RecentActivityList. The mock keeps the test focused on whether SalesDashboard renders and updates correctly.

// SalesDashboard.test.jsx
import { fireEvent, render, screen } from "@testing-library/react";
import SalesDashboard from "./SalesDashboard";

jest.mock("./RecentActivityList", () => {
return function MockRecentActivityList({ activities }) {
return (
<div data-testid="mock-activity-list">
Mock activity count: {activities.length}
</div>
);
};
});

describe("SalesDashboard", () => {
test("passes activities to the mocked child component", () => {
render(<SalesDashboard />);

expect(screen.getByTestId("mock-activity-list")).toHaveTextContent(
"Mock activity count: 3"
);
});

test("updates the activities sent to the mocked child component", () => {
render(<SalesDashboard />);

fireEvent.click(screen.getByRole("button", { name: "Add Activity" }));

expect(screen.getByTestId("mock-activity-list")).toHaveTextContent(
"Mock activity count: 4"
);
});
});

The jest.mock() call replaces the RecentActivityList module before the test renders SalesDashboard. The mock component receives the same activities prop as the real component, but it only displays the array length.

This test does not care about list item markup. It checks the parent’s job: it starts with three activities and sends four after the user clicks the button.

Sample test output:

PASS  SalesDashboard.test.jsx
SalesDashboard
✓ passes activities to the mocked child component
✓ updates the activities sent to the mocked child component

Pro Tip: I have found that a mock should stay small. If your mock recreates the child component’s full markup and logic, you lose the speed and clarity that mocking should provide.

Mock a React Component in Jest and Check Props

Sometimes you need to verify the exact props a parent sends to a child component. Jest lets you create a mock function and inspect its calls.

This approach works well for reusable dashboard widgets, table components, confirmation dialogs, and API-driven list views.

Use a Jest Mock Function

Create a mock function outside jest.mock(). Then return it from the mocked module.

// SalesDashboard.test.jsx
import { fireEvent, render } from "@testing-library/react";
import SalesDashboard from "./SalesDashboard";

const mockRecentActivityList = jest.fn(() => (
<div data-testid="mock-activity-list">Mocked activity list</div>
));

jest.mock("./RecentActivityList", () => ({
__esModule: true,
default: (props) => mockRecentActivityList(props),
}));

describe("SalesDashboard", () => {
beforeEach(() => {
mockRecentActivityList.mockClear();
});

test("sends the initial activity array to RecentActivityList", () => {
render(<SalesDashboard />);

expect(mockRecentActivityList).toHaveBeenCalledWith(
{
activities: [
{
id: 101,
salesRep: "Emily Carter",
customer: "Northwind Traders",
},
{
id: 102,
salesRep: "Michael Brooks",
customer: "Blue Ridge Supply",
},
{
id: 103,
salesRep: "Olivia Davis",
customer: "Greenfield Market",
},
],
},
undefined
);
});

test("sends the new activity after the button click", () => {
const { getByRole } = render(<SalesDashboard />);

fireEvent.click(getByRole("button", { name: "Add Activity" }));

const lastCall =
mockRecentActivityList.mock.calls[
mockRecentActivityList.mock.calls.length - 1
];

expect(lastCall[0].activities).toHaveLength(4);
expect(lastCall[0].activities[3]).toEqual({
id: 104,
salesRep: "Daniel Moore",
customer: "Summit Retail",
});
});
});

The mockRecentActivityList function records every call React makes to the mocked component. The first test checks the complete initial prop value. The second test reads the last call after the click and confirms that the parent passed the new activity.

The beforeEach() block clears previous mock calls. This keeps tests independent. Without it, calls from one test can affect another test.

Sample test output:

PASS  SalesDashboard.test.jsx
SalesDashboard
✓ sends the initial activity array to RecentActivityList
✓ sends the new activity after the button click

Use this level of prop testing carefully. Testing every prop on every render can make tests fragile. Test important behavior instead of implementation details whenever possible.

Mock a Named React Component Export

React files often export more than one component or helper. In that case, you must match the export style in your Jest mock.

Here is a child component with a named export.

// ActivitySummary.jsx
export function ActivitySummary({ totalActivities }) {
return (
<section>
<h2>Activity Summary</h2>
<p>Total activities: {totalActivities}</p>
</section>
);
}

This component exports ActivitySummary by name. It displays the number of activities received from its parent.

Sample output:

Activity Summary

Total activities: 3

Now update the dashboard to use it.

// SalesDashboard.jsx
import { useState } from "react";
import RecentActivityList from "./RecentActivityList";
import { ActivitySummary } from "./ActivitySummary";

function SalesDashboard() {
const [activities, setActivities] = useState([
{
id: 101,
salesRep: "Emily Carter",
customer: "Northwind Traders",
},
{
id: 102,
salesRep: "Michael Brooks",
customer: "Blue Ridge Supply",
},
{
id: 103,
salesRep: "Olivia Davis",
customer: "Greenfield Market",
},
]);

function addActivity() {
setActivities((currentActivities) => [
...currentActivities,
{
id: 104,
salesRep: "Daniel Moore",
customer: "Summit Retail",
},
]);
}

return (
<main>
<h1>Sales Activity Dashboard</h1>

<ActivitySummary totalActivities={activities.length} />

<button onClick={addActivity}>Add Activity</button>

<RecentActivityList activities={activities} />
</main>
);
}

export default SalesDashboard;

The parent calculates activities.length and passes that value to the named child component. React rerenders the dashboard after the state update, so the child receives the new total.

Sample output:

Sales Activity Dashboard

Activity Summary
Total activities: 3

[Add Activity]

Use this Jest mock for the named export.

// SalesDashboard.test.jsx
import { render, screen } from "@testing-library/react";
import SalesDashboard from "./SalesDashboard";

jest.mock("./ActivitySummary", () => ({
ActivitySummary: ({ totalActivities }) => (
<div data-testid="mock-summary">
Mock summary total: {totalActivities}
</div>
),
}));

jest.mock("./RecentActivityList", () => {
return function MockRecentActivityList() {
return <div>Mock activity list</div>;
};
});

describe("SalesDashboard", () => {
test("passes the activity total to the mocked named component", () => {
render(<SalesDashboard />);

expect(screen.getByTestId("mock-summary")).toHaveTextContent(
"Mock summary total: 3"
);
});
});

The mock object includes a property named ActivitySummary, which matches the named export. If your export name and mock property do not match exactly, Jest will not render the component correctly.

Sample test output:

PASS  SalesDashboard.test.jsx
SalesDashboard
✓ passes the activity total to the mocked named component

Mock a React Component With Children

Many React components receive children, which are the JSX elements placed between opening and closing component tags. Layout wrappers, modal windows, and permission components commonly use children.

Here is a simple dashboard panel.

// DashboardPanel.jsx
function DashboardPanel({ title, children }) {
return (
<section>
<h2>{title}</h2>
<div>{children}</div>
</section>
);
}

export default DashboardPanel;

The component receives a title prop and renders any nested JSX through children.

Sample output:

Sales Activity

Emily Carter updated Northwind Traders

Here is a parent component that uses the panel.

// SalesActivityPage.jsx
import DashboardPanel from "./DashboardPanel";

function SalesActivityPage() {
return (
<DashboardPanel title="Sales Activity">
<p>Emily Carter updated Northwind Traders</p>
</DashboardPanel>
);
}

export default SalesActivityPage;

This page wraps its paragraph inside DashboardPanel. The nested paragraph becomes the children prop.

Sample output:

Sales Activity

Emily Carter updated Northwind Traders

Now mock the wrapper while preserving its children.

// SalesActivityPage.test.jsx
import { render, screen } from "@testing-library/react";
import SalesActivityPage from "./SalesActivityPage";

jest.mock("./DashboardPanel", () => {
return function MockDashboardPanel({ title, children }) {
return (
<div data-testid="mock-dashboard-panel">
<strong>Mock panel: {title}</strong>
{children}
</div>
);
};
});

describe("SalesActivityPage", () => {
test("renders content inside the mocked panel", () => {
render(<SalesActivityPage />);

expect(screen.getByTestId("mock-dashboard-panel")).toHaveTextContent(
"Mock panel: Sales Activity"
);

expect(
screen.getByText("Emily Carter updated Northwind Traders")
).toBeInTheDocument();
});
});

The mock renders children intentionally. This lets you isolate the panel’s internal styling or layout code while still confirming that the parent places the correct content inside it.

Sample test output:

PASS  SalesActivityPage.test.jsx
SalesActivityPage
✓ renders content inside the mocked panel

Things to Keep in Mind

  • Mock only what you do not need to test: Keep the real child component when its rendered behavior matters to the user flow.
  • Match the export type: Use default in the mock for default exports and the exact function name for named exports.
  • Clear mock history: Call mockClear() in beforeEach() when you inspect mock calls across multiple tests.
  • Test behavior first: Check visible results, button actions, and important props before testing implementation details.
  • Render children when needed: A layout mock should render children if the parent test needs to verify nested content.
  • Keep mocks lightweight: Replace expensive API calls, charts, or complex child trees with simple test-friendly markup.

Frequently Asked Questions

How do I mock a React component in Jest?

Use jest.mock() with the relative path that the parent component imports. Return a small React component from the mock factory. Your mocked component can display a test ID, selected props, or children.

Why should I mock child components in Jest?

Mocking isolates the parent component from child complexity. It makes tests faster and easier to diagnose because failures point more clearly to the component under test.

How do I mock a default export React component?

Return a function directly from jest.mock() when the file uses export default. You can also return an object with __esModule: true and a default property when you need a reusable Jest mock function.

How do I mock a named export React component?

Return an object from jest.mock() with a property that matches the named export. For example, mock export function ActivitySummary() with { ActivitySummary: () => <div /> }.

Can I check props passed to a mocked React component?

Yes. Create a jest.fn() mock component and inspect mock.calls. This helps you verify that a parent sends the correct prop values after a user action or state change.

Should I mock every React component in a test?

No. Mock components that add unrelated complexity, such as charts, API wrappers, or third-party UI elements. Keep small and relevant child components real when their output supports the behavior you want to test.

Mocking a React component in Jest works best when you use it to isolate the parent component’s responsibility. Replace complex child components with focused test versions, verify important props when needed, and keep the tests centered on user-visible behavior.

You May Also Like

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.