How to Mock React Strict Mode
React’s Strict Mode is a valuable tool for identifying potential problems in an application, but its intentional double-rendering of components can cause headaches during unit testing. This article explains how to mock or disable React Strict Mode in your test environment using Jest or Vitest, as well as how to conditionally bypass it in your application’s entry point to keep your test suites predictable and clean.
Why Mock Strict Mode?
In development and testing environments, React’s
<StrictMode> intentionally double-mounts components
and fires effects twice to help find side effects. While beneficial in
development, this behavior can cause tests to fail
unexpectedly—especially when asserting the number of times a mock
function, API call, or event handler was called. Mocking Strict Mode
allows you to run tests in a single-render environment without changing
your production code behavior.
Method 1: Mocking React.StrictMode Globally
The most effective way to disable Strict Mode during testing is to
mock the react module. By replacing
React.StrictMode with a simple fragment wrapper, you ensure
that components render only once during tests.
If you are using Jest, add the following mock block
to your test file or your global setupTests.js file:
jest.mock('react', () => {
const originalReact = jest.requireActual('react');
return {
...originalReact,
StrictMode: ({ children }) => children,
};
});If you are using Vitest, the syntax is very similar:
import { vi } from 'vitest';
vi.mock('react', async () => {
const originalReact = await vi.importActual('react');
return {
...originalReact,
StrictMode: ({ children }) => children,
};
});With this mock in place, any component wrapped in
<React.StrictMode> will render normally, but without
the double-rendering and double-effect triggers.
Method 2: Conditional Rendering in the Entry Point
If you want to avoid mocking React internals, you can conditionally
render <StrictMode> in your application’s root entry
file (such as main.js or index.js) based on
the environment.
You can check the NODE_ENV variable to exclude Strict
Mode during tests:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
if (process.env.NODE_ENV === 'test') {
root.render(<App />);
} else {
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
}This approach completely prevents Strict Mode from mounting during tests, ensuring that your testing library (like React Testing Library) renders components exactly once.