Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
cleanup
2.1.
Example
2.2.
When to use cleanup()?
3.
act
3.1.
Example
3.2.
When to use act()?
4.
Frequently Asked Questions
4.1.
What is the difference between Jest and React testing library?
4.2.
What is shallow rendering in React Testing Library?
4.3.
How can one create a snapshot in React Testing Library?
4.4.
What does cleanup do in React testing library?
4.5.
Does Jest automatically cleanup?
5.
Conclusion
Last Updated: Mar 27, 2024

Cleanup and Act

Author Komal Shaw
0 upvote

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:

  1. Rendering a component tree and testing its output
  2. 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:-

  1. Data fetching(if you receive the response after the component disappeared)
  2. Event listener(timer, subscription)

act

When creating UI tests, tasks like rendering, user events, and data fetching can be seen as "units" of interaction with a user interface. Before making any assertions, the react-dom/test-utils' act() function makes sure that any changes pertaining to these "units" have been processed and applied to the DOM. As a result, your testing will be more representative of what actual users of your software could experience. However, using act() directly would be extremely time-consuming. To simplify things, we may utilize the act API from the React Testing Library.
 

The act API is nothing more than a simple wrapper for the act() function. Its duty is to pass all input arguments on to the act() function. In essence, it serves as a helper for the act() function, making the test simpler for the tester.

Example

The code to test elements with the act() function is:

import {act} from '@testing-library/react'
import ReactDOM from 'react-dom/client';
 
act(() => {
    ReactDOM.createRoot(xyz).render(<div />);     // the testing element rendered
});

When to use act()?

Wrap the code that renders and modifies a component in an act() call to make it ready for assertions. As a result, your test run is more similar to how React functions in a browser.
 

With act()

it('Should return some text', () => { 
act(() => { 
render(<TestComponent />, container); 
}); 
expect(container.textContent).toBe('some text'); 
})

 

Without act()

it('Should return some text', () => {
  render(<TestComponent />, container);
  expect(container.textContent).toBe('some text');
})

Frequently Asked Questions

What is the difference between Jest and React testing library?

Jest is a test runner that identifies and executes tests before determining whether they passed or failed. Jest also includes features for test suites, test cases, and assertions. React Testing Library is not a test runner and offers none of these features. It only provides a virtual DOM to test React components.

What is shallow rendering in React Testing Library?

Shallow rendering allows you to render a component "one level deep" and make assertions about what the renderer returns without worrying about its child components which are not rendered. Shallow rendering does not need a DOM.

How can one create a snapshot in React Testing Library?

You must first have functioning code before building snapshot tests for a React component. Then, input some data and create a snapshot of its predicted outcome. The component's snapshot tests are committed alongside it.

What does cleanup do in React testing library?

Unmounts React trees that were mounted with render.

Does Jest automatically cleanup?

If your testing framework has an afterEach hook, cleanup() is now called automatically after each test (like Jest, Mocha, and Jasmine).

Conclusion

This article discusses the role of the React Testing Libraries and then extensively discusses the working and uses of cleanup and act, two APIs contained within the React Testing Libraries.

We hope this blog has helped you enhance your knowledge regarding the Cleanup and Act. If you want to look at some more topics like Cleanup and Act, check out our articles on Angular Testing LibraryUtility APITesting Web Accessibility.

Refer to our guided paths on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must have a look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass