Features of Enzyme
- Shallow Rendering: Allows testing of a component in isolation by rendering only the component itself without its children, making it easier to test and debug.
- Full DOM Rendering: Provides the ability to render a component and its children, enabling more comprehensive testing that involves the full component tree.
- Static Rendering: Generates HTML from a component without running its lifecycle methods, useful for testing the output of simple components.
- Simulating Events: Provides methods to simulate user interactions like clicks, form submissions, and more, to test how components respond to events.
- Finding Elements: Offers intuitive methods to search for and find components and elements within the rendered output, making it easy to assert that the right elements are present and in the expected state.
Installation Command
Run the below command to install Enzyme:
npm install react enzyme enzyme-adapter-react-16 jest
Example: The example below shows how to set up Enzyme configuration
// setupTests.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
import { shallow } from 'enzyme';
test('button renders with correct text and handles click event', () => {
const wrapper = shallow(<button onClick={() => {}}>Click Me</button>);
wrapper.simulate('click');
});
Run the below command:
npm test
Compare React Testing Library and Enzyme for Testing React Components.
React Testing Library and Enzyme are widely used testing utilities for React components. Although they serve the same purpose, their approaches and features differ.