Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

How Do You Mock a React Component in Jest?

Replace a child module with a small React test double, then assert the parent’s user-visible behavior. The pattern depends on whether your project uses mock-hoisted imports or native ESM.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To mock a React child in Jest, replace its module with a small test component, then test the parent’s rendered output or interactions. For CommonJS or a Jest transform that supports mock hoisting, an inline factory is usually the simplest option. Native ECMAScript modules (ESM) require a different sequence: register the mock first, then dynamically import the dependency and the parent.

Mock a child component with an inline factory

Use jest.mock with the same module path the parent uses. The factory below supplies a valid, deliberately simple React component in place of ./Child:

As an Amazon Associate I earn from qualifying purchases.

jest.mock('./Child', () => () => <mock-child />);

This JSX form requires a test transform that supports JSX. If yours does not, return an element created with React.createElement instead:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
jest.mock('./Child', () => () => React.createElement('mock-child'));

Keep the placeholder focused on what the parent test needs. If the parent passes children or props that affect its behavior, the mock can render or use those values. Avoid returning the string 'Child' as a component type: Jest’s React tutorial warns that uppercase string tags can produce React warnings in snapshot tests. A lowercase custom element or simple text is a safer placeholder. Jest’s React testing tutorial shows DOM-based testing and discusses this mock-rendering caveat.

Test the parent’s behavior, not the child’s implementation

A child mock is useful when the parent test needs to isolate complex rendering or third-party behavior. It does not prove that the real child works. Keep assertions centered on what a user can see or do, such as parent-rendered text, an enabled state, or the result of an interaction. Jest’s React tutorial demonstrates rendering with @testing-library/react and making interaction assertions; it does not require mocking every child.

If the parent responds to a callback passed to its child, a behavior-bearing stub can expose a button that calls that callback. The test can then verify the parent’s response without recreating the child’s full implementation:

jest.mock('./Child', () => ({ onSave }) => (
  <button onClick={onSave}>Save</button>
));

Use this only when invoking that callback is part of the parent behavior being tested. Render the real child when the test’s purpose is to establish how parent and child work together.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the right mock pattern

Situation Pattern What to watch
One test file needs a purpose-built substitute Inline jest.mock('./Child', factory) Use the exact module path and a valid React render result.
Several tests need the same stable substitute A manual mock in a sibling __mocks__ directory For a user module, select it explicitly with jest.mock('./moduleName'). The folder name is case-sensitive.
The project uses native ESM jest.unstable_mockModule, followed by dynamic imports Static imports run before test code; the API is explicitly unstable.

Jest’s manual mocks guide explains module-level mocks, manual mock selection, and their scope. A manually maintained mock can drift from the real module; when appropriate, you can extend an automatic mock with jest.createMockFromModule.

Account for export shape and mock scope

For CommonJS modules or imports handled by a transform with Jest mock hoisting, jest.mock is generally registered before imports are evaluated. Keep the mock registration in the same test file and scope as the import or require that consumes the mock, and make the mock path match the path used by the parent. A mock declared in one test file does not automatically affect another test file.

If the mocked module has a default export and your factory returns an object, Jest’s factory conventions may require an object with __esModule: true and a default property. Match the real module’s export shape rather than adding these fields automatically:

jest.mock('./Child', () => ({
  __esModule: true,
  default: () => <mock-child />,
}));

Jest documents the factory and module-mocking mechanics in its manual mocks guide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Mock native ESM modules with dynamic imports

Do not rely on CommonJS-style jest.mock hoisting above static ESM imports. Static imports are evaluated before the test body, so register the ESM mock first and dynamically import both the dependency and the module under test afterward. The documented API is named jest.unstable_mockModule, and its unstable status is important: confirm that it fits your Jest and Node setup.

import { jest } from '@jest/globals';

jest.unstable_mockModule('./Child.js', () => ({
  default: () => React.createElement('mock-child'),
}));

const { default: Parent } = await import('./Parent.js');

This example assumes the parent imports ./Child.js as a default export and that React is available in the test. Adapt the path and returned export to the module under test. See Jest’s ECMAScript modules documentation for the ESM registration and loading requirements; behavior can also depend on the Node version and whether the module graph can be evaluated synchronously.

Update old mock-generation examples for Jest 30

If an older example uses jest.genMockFromModule, replace it with jest.createMockFromModule. Jest 30 removed the former API in favor of the latter, as stated in the Jest 30 upgrade guide. The current Jest documentation identifies its manual mock, mock function, and ESM guides as version 30.5; check the documentation and behavior for the Jest version installed in your project.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.