In this article, we will learn about React Testing Library and Enzyme, along with discussing the significant distinction that differentiates between React Testing Library and Enzyme.
Let us first understand about React Testing Library and Enzyme
React Testing Library:
It is a lightweight testing utility tool that’s built to test the actual DOM tree rendered by React on the browser. The goal of the library is to help you write tests that resemble how a user would use your application. The library does this by providing utility methods that will query the DOM in the same way a user would.
Features of React Testing Library :
1. User-Centric Testing: Instead of focusing on internal implementation details, it encourages developers to write tests that resemble how users interact with the application.
2. Queries for DOM Selection : React Testing Library provides a set of query functions for selecting elements from the DOM. For example :
const buttonElement = getByText(‘Click me’);
const inputElements = getAllByTestId(‘input-field’);
3. Event Simulation with fireEvent : The fireEvent utility in React Testing Library allows developers to trigger various events on DOM elements, such as clicks, changes, and keypresses. This ensures that the components respond correctly to user actions.
4. Async Testing with waitFor: React Testing Library provides the waitFor utility to handle asynchronous operations, waiting for a specified condition to be true or for a given timeout to elapse. This is particularly useful when dealing with components that fetch data asynchronously. For Example :
await waitFor(() => expect(getByText(‘Loaded’)).toBeInTheDocument());
5. Framework Independent : React Testing Library is designed to be framework-Independent , allowing developers to use it with various testing frameworks. Whether you’re using Jest, Mocha, or another testing library, React Testing Library seamlessly integrates into your testing environment.
How to Use React Testing Library ?
A React application created with Create React App (command to create a react app ) already includes both React Testing Library and Jest by default. So all you need to do is write your test code.
Note that , if you want to use React Testing Library outside of a CRA (Create React App ) application, then you need to install both React Testing Library and Jest manually with NPM
npm install --save-dev @testing-library/react jest
Installing React Testing Library and Jest
React Testing Library only provides methods to help you write the test scripts. So you still need a JavaScript test framework(e.g Jest) to run the test code
Example :
Javascript
import { render, screen } from '@testing-library/react';
const Greeting = ({ name }) => <h1>Hello, {name}!</h1>
test('renders greeting with name', () => {
render(<Greeting name="Alice" />);
expect(screen.getByText(/Hello, Alice!/i)).toBeInTheDocument();
});
Output:
Test Result
Above example tests a simple Greeting component that displays a greeting message with the provided name. It renders the component with “Alice” as the name, finds the element containing the greeting text using screen.getByText, and asserts its presence in the document using toBeInTheDocument.
Enzyme:
Enzyme is a JavaScript Testing utility for React that makes it easier to test your React Components’ output. It allows you to extract and manipulate the components of your React tree in order to test them. This makes it easier to write comprehensive tests that cover all aspects of your component.
Features of Enzyme :
1. Component Rendering Testing : Enzyme allow developers to render React components within the testing environment. Also it provide methods to render components with specific props and states for testing different scenarios.
2. Virtual DOM Support: Enzyme implement a virtual DOM for simulating the component rendering process without manipulating the actual DOM. It enable efficient and isolated testing of components in a controlled environment.
3. Shallow Rendering: Enzyme support shallow rendering to focus on testing the target component without rendering its child components. It facilitate faster and more focused testing by isolating the behavior of the primary component.
4. DOM Manipulation: It allow developers to simulate user interactions such as clicks, input changes, and form submissions and also provide a way to inspect the virtual DOM after these interactions to verify the expected changes.
5. Querying and Assertions: Enyme implement functions to query the rendered components using selectors similar to CSS selectors. It also support assertions to validate the state, props, and structure of the components.
6. Asynchronous Testing: Enzyme support testing of components that involve asynchronous operations such as data fetching . It provide mechanisms to handle asynchronous code and ensure reliable testing results.
How to Use Enzyme Testing Library ?
To use Enzyme in your React project, you need to install it. Here is the npm command for installing Enzyme :
npm install --save enzyme enzyme-adapter-react-17 enzyme-to-json
Example :
Below is an example for creating and testing a simple react component named ToggleButton . The ToggleButton component switches between ‘ON’ and ‘OFF’ states when clicked. The test verifies that the initial state is ‘OFF’ and that it toggles to ‘ON’ after a click.
Javascript
//App.js code
import React, { useState } from 'react';
const ToggleButton = () => {
const [isToggled, setToggle] = useState(false);
const handleClick = () => setToggle(!isToggled);
return (
<button onClick={handleClick}>
{isToggled ? 'ON' : 'OFF'}
</button>
);
};
export default ToggleButton;
Javascript
//Index.js code
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx'
ReactDOM.createRoot(
document.querySelector('#root')
).render(<App />)
Output
Server is listening to port: 8000
Web Output of React Code for Creating a ToggleButtion after Clicking on it
let’s write a test for our ToggleButton :
Javascript
// src/ToggleButton.test.js
import React from 'react';
import { shallow } from 'enzyme';
import ToggleButton from './ToggleButton';
describe('ToggleButton component', () => {
it('toggles between ON and OFF', () => {
const wrapper = shallow(<ToggleButton />);
// checking Initial States
expect(wrapper.text()).toBe('OFF');
// toggling a click on the button
wrapper.find('button').simulate('click');
// checking Updated States
expect(wrapper.text()).toBe('ON');
});
});
Output:
Terminal : Test result with Enzyme testing library
Difference between React Testing Library & Enzyme
Now after having an adequate understanding of both of them let us discuss the Key differences between React Testing Library and Enzyme testing library:
Feature | React Testing Library(RTL)
| Enzyme
|
---|
Development Timeline
| Developed in 2017 by Kent C. Dodds and the React community to encourage testing in a way that reflects how users interact with the application.
| Developed by Airbnb in 2015 to provide a comprehensive testing utility for React components .
|
Rendering Approach
| Uses a lightweight DOM testing library.
| Offers both shallow rendering and full rendering capabilities.
|
DOM Interaction
| RTL Uses queries like getBy, queryBy, findBy for more user-centric testing.
| Provides utility functions for DOM manipulation and querying, Enabling precise control.
|
Component Isolation
| RTL Focuses on testing components in a more isolated manner.
| Allows shallow rendering to isolate the tested component. It can also perform full rendering.
|
State and Props Access
| Limited direct access to component states and props.
| Enzyme Allows Direct access to component states and props .
|
Assertions
| Encourages making assertions based on user interaction and visible changes in the DOM.
| Supports various assertions, including snapshot testing for both shallow and deep tests.
|
Community Support
| Gained popularity for its simplicity and user-centric approach. Widely used in the React community.
| Popular for its longer presence, extensive community and comprehensive documentation.
|
Integration with Jest
| No direct integration with Jest; can be used independently or with other test runners.
| Officially integrated with Jest, making it seamless for projects using Jest as the test runner.
|
Learning Curve
| Generally considered easier to learn and beginner-friendly.
| Enzyme is considered hard to learn , especially for beginners but it offers more advanced features for experienced developers.
|
Conclusion:
No testing tool is objectively better than the other , you must consider the factors you have to account for when making a decision about which tool to use.
It’s clearly visible that react-testing-library simplifies this process of testing through its comprehensive set of helper methods for querying and the matchers from jest-dom. It is user-centric, emphasizing simplicity and adherence to user behavior, making it beginner-friendly and aligned with React’s principles. On the other hand, Enzyme provides a more extensive set of testing utilities, catering to various testing scenarios with both shallow and full rendering capabilities
Ultimately, the selection should be driven by the specific goals and characteristics of the project, ensuring effective and meaningful testing practices.Just make sure that you write tests that resemble user experience whenever possible.
Share your thoughts in the comments
Please Login to comment...