0
0
ReactHow-ToBeginner · 3 min read

How to Mock Component in React Test: Simple Guide

To mock a component in a React test, use jest.mock() to replace the component with a simple mock version. This lets you isolate the component under test and control its behavior without rendering its full implementation.
📐

Syntax

Use jest.mock() to replace a component module with a mock. Inside the mock, return a simple React component or a placeholder. Import the component you want to mock by its module path.

  • jest.mock('modulePath', () => mockImplementation): mocks the module at modulePath.
  • mockImplementation: a function returning a React component or mock.
javascript
jest.mock('./MyComponent', () => () => <div>Mocked Component</div>);
💻

Example

This example shows how to mock a child component inside a parent component test. The child is replaced with a simple mock that renders static text. This helps test the parent without running the child's real code.

javascript
import React from 'react';
import { render, screen } from '@testing-library/react';

// Mock the Child component
jest.mock('./Child', () => () => <div>Mocked Child</div>);

import Parent from './Parent';

test('renders Parent with mocked Child', () => {
  render(<Parent />);
  expect(screen.getByText('Mocked Child')).toBeInTheDocument();
});
Output
Test passes if 'Mocked Child' text is found in the rendered output.
⚠️

Common Pitfalls

  • Forgetting to mock the exact module path causes the real component to render.
  • Mocking after importing the component under test will not work; always mock before imports.
  • Mocking with a non-React function or missing JSX will cause errors.
  • Not resetting mocks between tests can cause unexpected results.
javascript
/* Wrong: mocking after import */
import Parent from './Parent';
jest.mock('./Child', () => () => <div>Mocked Child</div>); // This won't mock correctly

/* Right: mock before import */
jest.mock('./Child', () => () => <div>Mocked Child</div>);
import Parent from './Parent';
📊

Quick Reference

Remember these tips when mocking React components in tests:

  • Always call jest.mock() before importing the component under test.
  • Return a simple React component from the mock.
  • Use React Testing Library to verify rendered output.
  • Reset mocks between tests with jest.resetAllMocks() if needed.

Key Takeaways

Use jest.mock() before imports to replace components with mocks.
Mock components by returning simple React elements to isolate tests.
Verify mocked components render expected placeholders in tests.
Avoid mocking after imports to ensure mocks take effect.
Reset mocks between tests to prevent cross-test interference.