Table of contents
1.
Introduction
2.
Setup
2.1.
Program
2.2.
Test Program
2.3.
Output:
3.
Frequently Asked Questions
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

Triggering State Updates & Effects with “act”

Author Aman Thakur
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The article is in response to the issue rolled out in the official repository of react, which provides a way to trigger useEffect from test, which was introduced to the community on 1st Nov 2018 and was resolved on 9 Aug 2019. In this article, we will see how to update the state and test those up to see if that is properly working.

Let’s get started with it and see how we can proceed further.

Setup

For creating ReactJs, you can use the following command given below,

npx create-react-app <your-project-name>

Program

// src/Counter.js

import React, { Component } from "react";

export default class Counter extends Component {
 constructor(props) {
   super(props);
   this.state = { count: 0 };
   this.handleClick = this.handleClick.bind(this);
 }

 componentDidMount() {
   document.title = `you clicked ${this.state.count} times`;
 }

 componentDidUpdate() {
   document.title = `you clicked ${this.state.count} times`;
 }

 handleClick() {
   this.setState((state) => ({
     count: state.count + 1,
   }));
 }

 render() {
   return (
     <div>
       <p>you clicked {this.state.count} times</p>
       <button onClick={this.handleClick}>click me</button>
     </div>
   );
 }
}
You can also try this code with Online Javascript Compiler
Run Code
// src/App.js

import "./App.css";
import Counter from "./Counter";

function App() {
 return (
   <div className="App">
     <Counter />
   </div>
 );
}

export default App;
You can also try this code with Online Javascript Compiler
Run Code

Test Program

// src/Counter.test.js

import React from "react";
import ReactDOM from "react-dom";
import { act } from "react-dom/test-utils";
import Counter from "./Counter";

let container;

beforeEach(() => {
 container = document.createElement("div");
 document.body.appendChild(container);
});

afterEach(() => {
 document.body.removeChild(container);
 container = null;
});

it("can render and update a counter", () => {
 // Test first render and componentDidMount
 act(() => {
   ReactDOM.render(<Counter />, container);
 });
 const button = container.querySelector("button");
 const label = container.querySelector("p");
 expect(label.textContent).toBe("you clicked 0 times");
 expect(document.title).toBe("you clicked 0 times");

 // Test second render and componentDidUpdate
 act(() => {
   button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
 });
 expect(label.textContent).toBe("you clicked 1 times");
 expect(document.title).toBe("you clicked 1 times");
});
You can also try this code with Online Javascript Compiler
Run Code
// src/App.test.js

import { render } from "@testing-library/react";
import App from "./App";

test("renders learn react link", () => {
 render(<App />);
});
You can also try this code with Online Javascript Compiler
Run Code

Output:

Frequently Asked Questions

  1. How do you test for useEffect in React?
    Trigger state changes and look for effects in rendered elements to test the component update useEffect hook. Mocking redux hooks and their implementation may be used to test them.
     
  2. Can I have multiple useEffect in React?
    We may utilise many hooks in a single component using React. We could require numerous states in a single component, for example, so we can use multiple useState hooks in that component.
     
  3. What triggers a useEffect?
    By default, useEffect will fire whenever the React component is updated. This indicates that the effect will execute again if the component receives new props from its parent component or if the state is changed locally.
     
  4. What is the error boundary?
    React components that capture JavaScript problems anywhere in their child component tree, report them, and display a fallback UI instead of the component tree that failed are known as error borders. Error boundaries detect mistakes that occur during rendering, lifecycle methods, and constructors in the whole tree underneath them.

Conclusion

Hope you enjoyed reading this article and this article might have given you a proper understanding of creating a test case to trigger an act in the React and discussed few topics around it not only that we have created a project and tested it for the given use cases by figuring out from the official github repository.
If you are interested in testing, we strongly advise you to read our articles  Deep-Equal usages in chai, Mocha Assertions, and Introduction to Node.js if you want to further your knowledge in this area. We hope that this blog has increased your understanding of web-testing. Please upvote our blog if you like to read it.

Happy Learning!

Live masterclass