简体   繁体   中英

How correctly write Jest test for avoid act() warning?

useEffect usually use Promises for update state.

This updates cause long warning in jest: Warning: An update to null inside a test was not wrapped in act(...).

How correctly write Jest Test for such case?

live example, Reproducible Example:

https://codesandbox.io/s/jest-test-for-useeffect-with-promises-spieq?file=/index.test.js

index.test.js

import React from "react";
import Hello from "./Hello";
import { create, act } from "react-test-renderer";

it("works", () => {
  let root;
  act(() => {
    root = create(<Hello />);
  });

  // console.log("From test:", );
  let repr = JSON.stringify(root.toJSON());
  expect(repr).toBe('{"type":"span","props":{},"children":["Hello! "]}');
});

Hello.js

import React, { useState, useEffect } from "react";

export default () => {
  const [count, setCount] = useState();

  useEffect(() => {
    Promise.resolve({}).then(() => setCount(4));
  }, []);

  return <span>Hello! {count}</span>;
};

在此处输入图像描述

Upd 1:

the same result for one of propasal:

在此处输入图像描述

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();
});

Looks like this sample works correct

import React from "react";
import Hello from "./Hello";
import { render, screen, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom";

it("works", () => {
  render(<Hello />);
  return waitFor(() => screen.getByText("Hello! 4"));
  // expect(baseElement.toBeTruthy();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM