How to write a simple unit test using Enzyme?

Enzyme is a popular JavaScript testing library that allows you to test the components of your React applications in a simple and intuitive way. In this tutorial, we will go over the basics of setting up an enzyme unit test for a simple React component.


Before we get started, you will need to have the following tools installed on your machine:

  • Node.js and npm (or yarn)
  • A React project that you want to test
  • The enzyme library, which can be installed using the following command:
npm install --save-dev enzyme enzyme-adapter-react-16

Setting up the Test Environment

Before we can write our first enzyme test, we need to set up the test environment. This involves creating a test file and importing the necessary libraries and dependencies.

Here is an example of a test file that is set up to test a React component:

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

describe('MyComponent', () => {
  it('renders correctly', () => {
    const wrapper = shallow(<MyComponent />);

In this example, we have imported the shallow function from enzyme, which allows us to render a shallow version of our component. We have also imported the MyComponent component that we want to test.

Inside the describe block, we have defined a test case using the it function. This test case will render a shallow version of the MyComponent component and create a snapshot of it using the toMatchSnapshot function.

Writing a Test Case

Now that we have set up the test environment, let’s write a test case for our MyComponent component.

Here is an example of a test that checks if the component renders the correct text:

it('renders the correct text', () => {
  const wrapper = shallow(<MyComponent />);
  expect(wrapper.text()).toEqual('Hello, World!');

In this test case, we have used the text function provided by enzyme to get the text content of the component. We have then used the toEqual function to check if the text content is equal to the expected value of “Hello, World!”.

Wrapping Up

In this tutorial, we have gone over the basics of setting up an enzyme unit test for a simple React component. We have imported the necessary libraries and dependencies and written a test case that checks if the component renders the correct text.

Enzyme provides many other functions and features that allow you to test your React components in greater depth. You can find more information on these features in the Enzyme documentation.

I hope this tutorial has been helpful in getting you started with enzyme unit testing. Happy testing!

Leave a Reply

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

StackOverflow Profile