How correctly write Jest test for avoid act() warning?
I would like to suggest you to use testing-library/react which could be use smoothly with jest and provide async methods
Your test would become something like:
import React from "react";
import Hello from "./Hello";
import { render } from '@testing-library/react';
it("works", () => {
const { baseElement } = render(<Hello />);
expect(baseElement).toBeTruthy();
});
EDIT: For sake of completeness, in your example you're trying to test whether or not an update in your component happened after an effect which is using a promise.
In order to waitFor something async you can use the method findBy (findBy methods are a combination of getBy queries and waitFor.)
import React from "react";
import Hello from "./Hello";
import { render, findByText } from "@testing-library/react";
import "@testing-library/jest-dom";
it("works", async () => {
const { baseElement } = render(<Hello />);
expect(await findByText(baseElement, "Hello! 4")).toBeVisible();
});
Let's me explain, import "@testing-library/jest-dom"
allows you to use the the method toBeVisible
So, this test is rendering a component Hello and then it's waiting (with default value, 1000ms) inside the baseElement (which is the component itself) looking for the text "Hello! 4", then if found it will return the found element, which we are going to test whether is it visibile or not.