Introduce Enzyme and test React components

Test react with the Enzyme library. This will make your program more reliable and easier to avoid regressions. We used Jest here, but Enzyme can also be used with libraries like Mocha and Chai.

 

Enzyme Basics

Enzyme is a library for handling your react components at test time. It is developed by Airbnb.

Set up Enzyme

Continuing from the previous article, assuming your Jest is already working. If you haven't already, feel free to check out the previous section of the course. Let's start installing Enzyme

npm install enzyme

First create a setupTests.js file. It will contain usage of adapter, which is an add-on library that allows you to use Enzyme with a specific set of React versions. I will be using React 16.x, so need to install enzyme-adapter-react-16. Check out the Enzyme repo for a compatibility list.

You can also find adapters for libraries like preact and inferno
npm install enzyme-adapter-react-16

Once complete, the contents of the setupTests.js file should look like this:

setupTests.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
 
configure({adapter: new Adapter()});

The last thing to do is to provide the path to this file in package.json

package.json
"jest": {
    "setupTestFrameworkScriptFile": "<rootDir>/app/setupTests.js"
}

Ready!

Foshan vi designhttps://www.houdianzi.com/fsvi/ Pea Resources Search Daquanhttps://55wd.com

Shallow rendering

The most basic usage of the Enzyme library is shallow rendering. It allows you to render only the parent component. "Shallow rendering" is not only faster, but also great for unit testing. This way, you are no more than testing components passed to the shallow function.

App.js
import React from 'react';
 
const App = () => {
  return <h1>Hello world!</h1>
}
 
export default App;
App.test.js
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';
 
describe('app component', () => {
  it('contains a header with the "Hello world!"', () => {
    const app = shallow(<App/>);
    expect(app.containsMatchingElement(<h1>Hello world!</h1>)).toEqual(true);
  });
});

In this simple test, we are checking if the App component contains a certain header. After running npm run test you will see a success message.

PASS  app/App.test.js
  app component
    ✓ contains a header with the "Hello world!"

A very important point to note here: even though we use Enzyme, the test runner is still Jest. Since we're using the expect function, there are various matcher functions that can be called. I already mentioned them in the first part of the course. For a related list, visit the Jest documentation.

Let's create some more interesting tests. Start by creating a brand new component.

ToDoList.js
import React from 'react';
 
const ToDoList = (props) => {
  return (
    <ul>
      {
        props.tasks.map((taskName, index) =>
          <li key={index}>{taskName}</li>
        )
      }
    </ul>
  )
};
 
export default ToDoList;

Let's test what happens if the provided task list is empty, and what happens if it contains tasks.

ToDoList.test.js
import React from 'react';
import { shallow } from 'enzyme';
import ToDoList from './ToDoList';
 
describe('ToDoList component', () => {
  describe('when provided with an empty array of tasks', () => {
    it('contains an empty <ul> element', () => {
      const toDoList = shallow(<ToDoList tasks={[]}/>);
      expect(toDoList).toContainReact(<ul/>);
    })
    it('does not contain any <li> elements', () => {
      const toDoList = shallow(<ToDoList tasks={[]}/>);
      expect(toDoList.find('li').length).toEqual(0);
    })
  });
 
  describe('when provided with an array of tasks', () => {
    it('contains a matching number of <li> elements', () => {
      const tasks = ['Wash the dishes', 'Make the bed'];
      const toDoList = shallow(<ToDoList tasks={tasks}/>);
      expect(toDoList.find('li').length).toEqual(tasks.length);
    })
  });
});

The test passed without a hitch, but we should explain a few things.

In the first test, we used the toContainReact function, which is a custom matcher function. It is part of the enzyme-matchers library. To use it with Jest, install the jest-enzyme package.

npm install jest-enzyme

The last thing to do is import it in the setupTests file.

setupTests.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'jest-enzyme';
 
configure({adapter: new Adapter()});

For a list of the features it provides, check out the README. You will find it very useful.

In the second test, we call the find function on the component. This is thanks to the shallow function returning ShallowWrapper, which is a wrapper around the rendered output. It has a set of functions to call. To check the list of functions, go to the Enzyme documentation.

Running all the tests will give us success messages!

PASS  app/App.test.js
PASS  app/components/ToDoList/ToDoList.test.js
 
Test Suites: 2 passed, 2 total
Tests:       4 passed, 4 total
Snapshots:   0 total
Time:        1.41s
Ran all test suites.

 

Summarize

In this article we have learned the basics of testing React components with Enzyme. We've covered installing Enzyme and running our first simple test. The type of rendering used is called "Shallow Rendering". It's called that because it doesn't render any child components. When writing unit tests, it works just fine. In later parts of this tutorial, I'll cover other types of rendering and learn how to test different parts of the program. It will include techniques like snapshot testing and mock data. See you next time!

Tags: Framework

Posted by EvilSupahFly on Wed, 11 May 2022 14:54:41 +0300