How to Mock React Props in Unit Tests

Testing React components often requires simulating different inputs to ensure they render and behave correctly. This article provides a straightforward guide on how to mock React props using popular testing tools like Jest and React Testing Library, covering basic data props, mock functions, and prop updates during a test.

Mocking Basic Data Props

The simplest way to mock React props is to define a mock data object or variable in your test file and pass it directly to the component when rendering. Because props are just JavaScript objects passed to a function, you do not need any special configuration for static data like strings, numbers, arrays, or objects.

// UserProfile.test.js
import { render, screen } from '@testing-library/react';
import UserProfile from './UserProfile';

test('renders user profile with mocked data props', () => {
  // Define mock props
  const mockUser = {
    name: 'Jane Doe',
    role: 'Administrator'
  };

  // Pass mock props to the component
  render(<UserProfile user={mockUser} />);

  // Assert expected behavior
  expect(screen.getByText('Jane Doe')).toBeInTheDocument();
  expect(screen.getByText('Role: Administrator')).toBeInTheDocument();
});

Mocking Function Props (Callbacks)

When testing user interactions, components often rely on callback functions passed as props (such as onClick or onSubmit). To verify that these functions are called correctly, you can mock them using Jest’s spying and mocking utility, jest.fn().

// CustomButton.test.js
import { render, screen, fireEvent } from '@testing-library/react';
import CustomButton from './CustomButton';

test('calls the mock function when clicked', () => {
  // Create a mock function
  const mockHandleClick = jest.fn();

  // Pass the mock function as a prop
  render(<CustomButton label="Click Me" onClick={mockHandleClick} />);

  // Trigger the click event
  fireEvent.click(screen.getByRole('button', { name: /click me/i }));

  // Assert the mock function was called
  expect(mockHandleClick).toHaveBeenCalledTimes(1);
});

Updating Props During a Test

Sometimes you need to test how a component responds when its props change over time. React Testing Library provides a rerender function returned by the initial render method, allowing you to pass new props to the same mounted component.

// StatusDisplay.test.js
import { render, screen } from '@testing-library/react';
import StatusDisplay from './StatusDisplay';

test('updates UI when props change', () => {
  // Initial render with offline status
  const { rerender } = render(<StatusDisplay status="offline" />);
  expect(screen.getByText('User is offline')).toBeInTheDocument();

  // Rerender the same component with online status
  rerender(<StatusDisplay status="online" />);
  expect(screen.getByText('User is online')).toBeInTheDocument();
});