How to test components with React.StrictMode in React using Enzyme?

May 21, 2025

Leave a message

Michael Brown
Michael Brown
Plant Biologist specializing in kiwifruit cultivation. With 1 million acres dedicated to kiwi plantations, my role involves optimizing growth conditions and extracting the best nutrients from these superfruits for our powders.

Testing components in React is a crucial part of the development process, ensuring that your application functions as expected and remains stable as it evolves. React.StrictMode is a valuable tool that helps you identify potential problems in your components during development. In this blog post, as an Enzyme supplier, I'll guide you through the process of testing components with React.StrictMode using Enzyme.

Understanding React.StrictMode

React.StrictMode is a wrapper component provided by React that activates additional checks and warnings for its descendants. It doesn't render any visible UI; instead, it helps you find common mistakes and potential issues in your components. When you wrap a part of your application with React.StrictMode, React will perform extra checks such as detecting legacy lifecycle methods, warning about improper usage of the useState and useReducer hooks, and identifying unexpected side effects.

import React from 'react';

const App = () => {
    return (
        <React.StrictMode>
            {/* Your components go here */}
        </React.StrictMode>
    );
};

export default App;

Why Use Enzyme for Testing?

Enzyme is a JavaScript testing utility for React that makes it easier to test your React components' output. It provides a set of methods to manipulate, traverse, and query your React components' virtual DOM. With Enzyme, you can simulate user interactions, test component states, and verify the rendered output. As an Enzyme supplier, I can attest to its flexibility and ease of use, which makes it a popular choice among React developers for testing.

Setting Up the Testing Environment

Before you start testing your components with React.StrictMode using Enzyme, you need to set up your testing environment. First, you'll need to install the necessary packages. If you're using npm, you can run the following commands:

npm install --save-dev enzyme enzyme-adapter-react-16 react-test-renderer

Here, enzyme is the testing utility, enzyme-adapter-react-16 is the adapter for React 16 (you may need to adjust the version according to your React version), and react-test-renderer is used to render React components to pure JavaScript objects.

Next, you need to configure Enzyme to use the adapter. You can do this in a setup file, for example, setupTests.js:

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });

Writing Tests with React.StrictMode and Enzyme

Let's assume you have a simple React component called Button that renders a button with some text.

import React from 'react';

const Button = ({ text }) => {
    return <button>{text}</button>;
};

export default Button;

Now, let's write a test for this component using Enzyme and React.StrictMode.

import React from 'react';
import { shallow } from 'enzyme';
import Button from './Button';

describe('Button component', () => {
    it('should render the correct text', () => {
        const text = 'Click me';
        const wrapper = shallow(<React.StrictMode><Button text={text} /></React.StrictMode>);
        const button = wrapper.find('button');
        expect(button.text()).toBe(text);
    });
});

In this test, we use the shallow rendering method from Enzyme to render the Button component wrapped in React.StrictMode. Then, we find the button element using the find method and verify that the text inside the button matches the text prop we passed.

Testing Component State Changes

Enzyme also allows you to test component state changes. Let's say you have a component called Counter that has a state variable count and a button to increment the count.

import React, { useState } from 'react';

const Counter = () => {
    const [count, setCount] = useState(0);

    const increment = () => {
        setCount(count + 1);
    };

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={increment}>Increment</button>
        </div>
    );
};

export default Counter;

Here's how you can test the state change in this component:

import React from 'react';
import { mount } from 'enzyme';
import Counter from './Counter';

describe('Counter component', () => {
    it('should increment the count when the button is clicked', () => {
        const wrapper = mount(<React.StrictMode><Counter /></React.StrictMode>);
        const button = wrapper.find('button');
        const initialCount = parseInt(wrapper.find('p').text().split(': ')[1], 10);
        button.simulate('click');
        const newCount = parseInt(wrapper.find('p').text().split(': ')[1], 10);
        expect(newCount).toBe(initialCount + 1);
    });
});

In this test, we use the mount method from Enzyme to render the Counter component wrapped in React.StrictMode. We then find the button, get the initial count value, simulate a click on the button, and verify that the count has been incremented.

Testing Component Lifecycle Methods

React.StrictMode can help you detect legacy lifecycle methods in your components. Let's say you have a component with a legacy componentWillReceiveProps method.

import React, { Component } from 'react';

class LegacyComponent extends Component {
    componentWillReceiveProps(nextProps) {
        // Some logic here
    }

    render() {
        return <div>{this.props.text}</div>;
    }
}

export default LegacyComponent;

When you test this component with React.StrictMode, React will issue a warning about the usage of the legacy lifecycle method.

import React from 'react';
import { shallow } from 'enzyme';
import LegacyComponent from './LegacyComponent';

describe('LegacyComponent', () => {
    it('should render correctly', () => {
        const text = 'Hello';
        const wrapper = shallow(<React.StrictMode><LegacyComponent text={text} /></React.StrictMode>);
        expect(wrapper.find('div').text()).toBe(text);
    });
});

This warning helps you identify and update your components to use the new lifecycle methods or hooks.

Asclepius Supply High Quality Psicose Powder /d Psicose PowderMedium Chain Triglycerides

Testing Hooks

If your component uses hooks, React.StrictMode can also help you detect potential issues. For example, let's say you have a custom hook that fetches data from an API.

import React, { useState, useEffect } from 'react';

const useFetch = (url) => {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await fetch(url);
                const json = await response.json();
                setData(json);
            } catch (error) {
                console.error(error);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, [url]);

    return { data, loading };
};

const DataFetcher = ({ url }) => {
    const { data, loading } = useFetch(url);

    if (loading) {
        return <p>Loading...</p>;
    }

    return <pre>{JSON.stringify(data, null, 2)}</pre>;
};

export default DataFetcher;

Here's how you can test this component:

import React from 'react';
import { mount } from 'enzyme';
import DataFetcher from './DataFetcher';

describe('DataFetcher component', () => {
    it('should render loading text initially', () => {
        const url = 'https://example.com/api/data';
        const wrapper = mount(<React.StrictMode><DataFetcher url={url} /></React.StrictMode>);
        expect(wrapper.find('p').text()).toBe('Loading...');
    });
});

React.StrictMode will ensure that the useEffect hook in the useFetch custom hook is called correctly and that there are no unexpected side effects.

Conclusion

Testing components with React.StrictMode using Enzyme is an effective way to ensure the quality and stability of your React applications. React.StrictMode helps you identify potential issues early in the development process, while Enzyme provides a powerful set of tools for testing your components. As an Enzyme supplier, I encourage you to incorporate these testing practices into your development workflow.

If you're interested in high-quality enzyme products or other related supplies, we also offer a range of products such as Asclepius Supply High Quality Psicose Powder /d Psicose Powder, Natural Phosphatidylserine 70%,Powdered Phosphatidylserine, and Medium Chain Triglycerides. If you have any questions or would like to discuss a potential purchase, please don't hesitate to contact us for further details and to start a procurement negotiation.

References

  • React Documentation: https://reactjs.org/docs/strict-mode.html
  • Enzyme Documentation: https://enzymejs.github.io/enzyme/
Send Inquiry