Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Reasons to choose RTL
3.
Getting Started
4.
Installation
4.1.
Import RTL
5.
Examples of Migration
5.1.
React Component
5.2.
Program
5.3.
Test
5.3.1.
Enzyme Test
5.3.2.
RTL Test
6.
Frequently Asked Questions
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Migrating from Enzyme

Introduction

This blog describes the process of migrating from enzyme to React Testing Library. If you are currently using Enzyme and want to migrate to RTL, you are at the right place.

This blog explains how to install and import React Testing Library to your project and explains the migrations using examples. This blog assumes you are familiar with RTL.

Reasons to choose RTL

Enzyme is a sophisticated test library, and its creators have made significant contributions to the JavaScript community. Many of the React Testing Library maintainers utilised and contributed to Enzyme for years before starting to work on React Testing Library. As a result, we'd want to express our gratitude to Enzyme's contributors!

The main goal of the React Testing Library is to boost your test confidence by simulating how a user might interact with your components. Users are unconcerned about what happens behind the scenes; all they care about is what they see and how they engage with it. You'll get more confidence by building your tests based on the component output rather than accessing the components' internal APIs or evaluating their state.

The goal of the React Testing Library is to tackle a problem that many developers have while building tests with Enzyme, which allows (and encourages) developers to test implementation details. This type of test prevents you from updating or refactoring the component without changing the tests. As a result, the tests slow down the rate of development and reduce productivity. Even if the modification has no effect on the component's output, every tiny change may necessitate rewriting some element of your tests.

It's worthwhile to rewrite your tests in the React Testing library since you'll be trading tests that slow you down for tests that offer you greater confidence and boost your productivity in the long run.

Getting Started

To guarantee a smooth transition, we recommend running the two test libraries side by side in the same application and transferring your Enzyme tests one by one to the React Testing Library. Because the process can be done collaboratively and spread out over time, even large and complicated systems may be migrated without impacting other businesses.

Installation

Install the React Testing Library as well as the jest-dom helper library first (you can check this page for the complete installation and setup guide).

npm install --save-dev @testing-library/react @testing-library/jest-dom

Import RTL

You just need to import the following modules into your test file if you're using Jest (other test frameworks are also acceptable).

// import React so you can use JSX (React.createElement) in your test
import React from 'react'


/**
 * render: lets us render the component as React would
 * screen: a utility for finding elements the same way the user does
 */
import {render, screen} from '@testing-library/react'


The structure of the test can be the same as with Enzyme:


test('test title', () => {
  // Your tests come here...
})

Examples of Migration

One thing to bear in mind is that Enzyme features do not map directly to React Testing Library features. Many Enzyme features result in inefficient tests in the first place, therefore some of the features you're used to with Enzyme need to go (no more wrapper variables or wrapper.update() calls, for example).

The React Testing Library includes queries that allow you to access the elements and attributes of your component. We'll go through some common Enzyme tests as well as several React Testing Library alternatives.

Let's imagine we have a Welcome component that displays a greeting. To learn how to test this component, we'll look at both Enzyme and React Testing Library tests:

React Component

The next component uses props to acquire a name and displays a welcome message in a h1 element. It also features a text entry that users can change to a different name, which causes the template to update.

Program

const WelcomeText = (props) => {
 const [values, setValues] = useState({
   first_name: props.first_name,
   last_name: props.last_name,
 });

 const changeHandler = (event) => {
   setValues({ ...values, [event.target.name]: event.target.value });
 };

 return (
   <div>
     <h1>
       Welcome, {values.first_name} {values.last_name}
     </h1>

     <form name="userName">
       <label>
         First Name
         <input
           value={values.first_name}
           name="first_name"
           onChange={changeHandler}
         />
       </label>

       <label>
         Last Name
         <input
           value={values.last_name}
           name="last_name"
           onChange={changeHandler}
         />
       </label>
     </form>
   </div>
 );
};

export default WelcomeText;

Test

Let us create a test in RTL and Enzyme to check if h1 value is correctly rendered.

Enzyme Test

test('has correct welcome text', () => {
  const wrapper = shallow(<Welcome first_name="John" last_name="Doe" />)
  expect(wrapper.find('h1').text()).toEqual('Welcome, John Doe')
})

RTL Test

test('has correct welcome text', () => {
  render(<Welcome first_name="John" last_name="Doe" />)
  expect(screen.getByRole('heading')).toHaveTextContent('Welcome, John Doe')
})

As you can see, the tests are pretty similar. Enzyme's shallow renderer doesn't render sub-components, so React Testing Library's render method is more similar to Enzyme's mount method.

Frequently Asked Questions

1. Does the React testing library replace enzymes?
Ans: React Testing Library doesn't replace Jest, just Enzyme.

 

2. Can you use both Enzyme and React testing library?
Ans: Both Enzyme and react-testing-library have great documentation, but I believe that the Enzyme API leans you towards testing implementation (state and props) whilst react-testing-library leans you towards testing user behavior.
 

3. How do you test React with Jest and enzyme?
Ans: Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.

Conclusion

In this blog, we extensively discussed the process of migration from Enzyme to React Testing Library. We saw how to install and import RTL and understood an example of migration from Enzyme.
We hope that this blog has helped you enhance your knowledge regarding the process of migration from Enzyme to RTL and if you would like to learn more, check out our articles on Jest and React Test Utilities. Do upvote our blog to help other ninjas grow.

Live masterclass