Introduction
One of the primary elements in designing a product is testing it before release. It provides reassurance about the product's reliability and quality. Testing is mostly carried out with React in two different ways:
- Rendering a component tree and testing its output
-
Executing the entire app to check the output
To test out UI components in a React application, the first option—to render only particular components—is frequently utilized. These tests are carried done using the Testing Library family of packages.
The central library in the family of testing libraries is DOM Testing Library. It is a compact package that tests web pages using DOM nodes. This is necessary but insufficient to test all UI component features. The React Testing Library, a library built on top of the DOM Testing Library with additional support for APIs for executing React components, can be used to obtain a much better testing environment.
We'll examine cleanup and act, two of the React Testing Library's most crucial APIs, in this article. We'll observe their operation and the applications of cleanup and act.
cleanup
React trees were frequently mounted onto the renderer during testing so that they could be tested. Then, in order to prevent a memory leak, these React trees would need to be unmounted. A memory leak during the test would result in unneeded errors. So, the cleanup API is now available, which can unmount these unnecessary React trees and release RAM.
It's crucial to remember that cleanup requires manual intervention and must be initiated by the tester. The afterEach global, supported by some testing frameworks (including mocha, Jest, and Jasmine), can automatically initialize the cleanup API.
Example
When we are using the ava framework, the test code for cleanup would be:
import {cleanup, render} from '@testing-library/react'
import test from 'ava'
test.afterEach(cleanup)
test('render components', () => {
render(<div />)
// test elements
})
When to use cleanup()?
To avoid a memory leak, which takes up space unnecessarily due to running or neglecting to clean a function. Someone (especially a novice) might believe that since it is still functional, there is no need to worry about memory leaks. However, in order to optimize, the site's speed and computer performance must be improved.
The situation needs a clean-up function:-
- Data fetching(if you receive the response after the component disappeared)
- Event listener(timer, subscription)