Testing computer programs, especially ones written using React, can be tricky. However, opting for a React testing library can save you a lot of hassle. Enzyme and React-testing-library are two popular options out there.
Enzyme has been in existence for a decent amount of time now, having been released back in 2015. In contrast, react-testing-library was introduced more recently in 2018, and, quickly gained popularity. However, according to 2019 State of JavaScript Survey, both these libraries are pretty popular tools for testing React.
And in this article, we will look in how React-testing-library and Enzyme stack against each other and even run some tests together. The idea is to help you test out these libraries before you deploy your React app.
What is Enzyme testing library?
Enzyme is a popular JavaScript testing library primarily used for unit testing in React applications. Often used in conjunction with Jest, it has been available since 2015, resulting in a well-established ecosystem with comprehensive coverage of potential issues. Later in this post, we will provide examples of test cases that utilize Enzyme.
What is React-testing-library?
Built on top of the DOM Testing Library, the React Testing Library quickly gained popularity after its release in 2018. With the help of this testing framework, developers may create test cases that replicate real-world occurrences, like a user hitting a button, simulating genuine user contact. We will also use the React Testing Library to demonstrate a few test cases later in this session.
React component testing tools
Developers are starting to think differently when it comes to testing React components. Before a feature or product is released onto the market, software testing is done to find and report any bugs in the application and ensure that the release is reliable.
There is a clear difference between react-testing-library and enzyme in terms of testing structure. It is simple to create tests that faithfully capture the user experience of the application with the react-testing-library. You test the application as though you are the user interacting with it when you write tests with the react-testing-library.
However, it can be a little trickier to write tests with Enzyme and still have the same level of confidence as with react-testing-library. This is due to the fact that developing a test structure that accurately mimics the way an actual user would interact with the application may be more challenging.
Sample React components suitable for testing
Apart from the primary distinctions between functional and class components in React, there exist multiple other aspects that could impact your decision regarding the tool you use for your subsequent project. In order to demonstrate this, I have created a basic component concept utilising both methods, enabling us to contrast the test frameworks for every kind of component.
We'll be developing a component known as RangeCounter. It will feature a display of the current count between these buttons in addition to two control buttons for adding and subtracting. The lowest and maximum values of the properties supplied to the component will decide the count.
The user will be prompted with an alert message explaining why they are unable to proceed with incrementing or decreasing the number if they reach either the minimum or maximum value.
If you are interested in seeing the complete code, including tests, a GitHub repository is available for you to use alongside this post.
Class component example
Functional component example
Testing with Enzyme vs. React-testing-library
For both the class and functional components, we will conduct the following tests using each of these testing tools:
- Verify that the user can increase the count when it is allowed to be incremented.
- Ensure that the alert message appears only when the user has edited the count and reached either the minimum or maximum limit.
Enzyme Testing: Can the user increment the counter when it is allowed?
Let’s have a look at the first scenario using Enzyme.
This code is a test case for the RangeCounterClass component using the Enzyme testing library. It tests whether the counter value updates correctly when incrementing is allowed. It sets up a test suite with a describe block for the RangeCounterClass component and a beforeEach block to create a shallow wrapper of the component before each test. Then, there is a describe block for the scenario where incrementing is allowed, and it block that calls the incrementCounter method of the component instance and checks that the state of counter and hasEdited have been updated as expected using the expect function.
The test code ensures that the component works correctly by checking the received props and the component's state. If the test passes, it is assumed that the displayed count is the same as the counter-state variable. The test also verifies whether the hasEdited variable has changed to true after programmatically updating the counter, which indicates whether the alert should be displayed or not.
React-testing-library : Can the user increment the counter when it is allowed?
Now let’s try the same test scenario but now let us use the react-testing-library:
The above code block is an example of a test written using react-testing-library. It tests the RangeCounterB functional component to see if the counter value updates correctly when incrementing is allowed.
First, it renders the component with a minimum value of 2. Then it gets the increment button using getByText and simulates a click on it using fireEvent.click. Finally, it checks if the counter value has updated to 3 using getByTestId and expect.
The purpose of this test is to verify the user interface display, which is achieved by retrieving the actual DOM element and checking its content. The following three scenarios in the list use a similar approach. The last scenario, however, is particularly noteworthy as it shows that Enzyme can be used to test the same concept as react-testing-library.
Enzyme Test: Does alert message only show after editing and reaching limit?
The code block shows a test suite using Enzyme's shallow rendering method to test a component called RangeCounterClass. The beforeEach function is used to initialize the component before each test case.
The it function describes the behaviour being tested, which is if the component displays an alert message when the range limit is reached by clicking the control buttons. The component is re-initialized with specific props to simulate the range limit.
The instance method is used to simulate an increment action that will reach the maximum limit. The update method is then called to trigger a re-render of the component.
The test checks if the alert message is rendered with the correct text by finding the element with the .RangeCounter__alert class and comparing its text content with the expected value using the toEqual matcher.
React-testing-library Test: Does alert message only show after editing and reaching limit?
This code is a test case using react-testing-library to check if the "Range limit reached!" alert message has shown up when the user has reached the max limit by clicking the increment button. It renders the RangeCounterB component with min and max props and gets the increment button by text. Then, it clicks the button and asserts that the alert message is visible.
How Enzyme and React-testing-library conducted these tests
Although they accomplish it in different ways, Enzyme and react-testing-library both verify that the alert is displayed on the website.Even though consumers aren't shown that information in the user interface, Enzyme frequently looks for components on the page according to their class. Enzyme checks its contents to make sure it matches what the user sees after obtaining the element.
Conversely, react-testing-library searches are conducted based on the text that the user really sees. Applying Enzyme to the same notion could be more difficult if your HTML structure is more complicated and has a lot of child components.It is possible to move tests from one tool to another, however it could necessitate some modifications.
Migrating from Enzyme to React-testing-library
It is relatively simpler to migrate from Enzyme to react-testing-library as compared to the reverse. The strategy is to start using both of these libraries in your React app, and then one by one convert your Enzyme tests to RTL tests. Once this is done, you can remove all your Enzyme dependencies and stick to React Testing Library for future.
Migrating from React-testing-library to Enzyme
To switch from react-testing-library to Enzyme, you'll need to add an extra library called enzyme-adapter-react-[react-version]. This adapter library is essential, and its setup steps vary depending on your React version. Enzyme's adapters currently support up to React v.16, and there's an unofficial adapter for React v.17. Unfortunately, there's no adapter for React v.18 as of now.
After installing the adapter, you can choose your preferred test runner as Enzyme. Now you can start modifying your tests in RTL to run in Enzyme.
React-testing-library vs Enzyme
Determining whether React-testing-library or Enzyme is better depends on various factors. Here is a brief React-testing-library vs Enzyme comparison.
Conclusion
In conclusion, whether you have built your app from scratch or are using Bootstrap in React, both Enzyme and React-testing-library can be good options to explore. However chosing a React Testing Library ultimately depends on the specific needs of your project.
React-testing-library is better suited for testing user behaviour, while Enzyme may be better for matching the state of React or other functions with the state. Both tools have their limitations and benefits, and it's important to consider which tool will provide the most effective testing for your particular use case.
Happy testing!