Introduction
When it comes to testing ReactJS components, a popular tool is enzyme. Enzyme provides a set of utilities that make it easier to assert, manipulate, and traverse React components. One of the key features of enzyme is its shallow rendering capability, which allows you to render a component without rendering its children.
In this tutorial, we will explore how to use enzyme’s shallow rendering feature to isolate and test individual React components.
Setting up the project
To get started, let’s create a new React project and install enzyme as a dev dependency:
$ npx create-react-app my-app
$ cd my-app
$ npm install --save-dev enzyme enzyme-adapter-react-16
Next, we need to configure enzyme to work with React 16. Create a new file called setupTests.js
in the src
folder with the following contents:
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
This file initializes the enzyme adapter for React 16.
Writing the component
Let’s say we have a simple Button
component that renders a button element with a given label:
import React from 'react';
const Button = ({ label }) => <button>{label}</button>;
export default Button;
Testing the component using shallow rendering
Now, let’s write some tests for our Button
component using enzyme’s shallow rendering. Create a new file called Button.test.js
in the same directory as the Button.js
file.
import React from 'react';
import { shallow } from 'enzyme';
import Button from './Button';
describe('Button component', () => {
it('renders the button with the correct label', () => {
const label = 'Click me';
const wrapper = shallow(<Button label={label} />);
expect(wrapper.text()).toBe(label);
});
});
In this test, we use shallow
to render the Button
component without rendering its child components. We then use the text
method provided by enzyme to assert that the rendered button has the correct label.
Running the tests
To run the tests, we can use the following command:
$ npm test
This will run all the tests in our project, including the newly created Button
component test.
Conclusion
Enzyme’s shallow rendering feature is a powerful tool for isolating and testing individual React components. It allows you to focus on testing the behavior of a component without worrying about its child components. By using shallow rendering, you can write more focused and efficient tests for your React applications.