React-testing-library: Still see Warning about 'act' with useEffect updating state

Created on 13 Aug 2019  路  1Comment  路  Source: testing-library/react-testing-library

  • react-testing-library version: 9.1.1
  • react version: 16.9.0
  • node version: 8.11.3
  • npm (or yarn) version: 1.17.3

Relevant code or config:

https://codesandbox.io/embed/agitated-snyder-mvvgi

Component:

import React, { useState } from "react";
import loadData from "./loadData";

const App = () => {
  const [name, setName] = useState("Roux");
  React.useEffect(() => {
    loadData().then(newName => {
      setName(newName);
    });
  });
  return (
    <div className="App">
      <h1>Hello {name}</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
};

export default App;

Test:

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

describe("App", () => {
  it("renders", async () => {
    const { container } = render(<App />);
    expect(container).toBeDefined();
  });
});

What you did:

I have been following the conversation here: https://github.com/testing-library/react-testing-library/issues/281 and today tried to upgrade react & testing library so I could remove the console "hack".

What happened:

I am still seeing the error, specifically when I render a component that uses useEffect to update state after calling an async function (the real world use case here is an API that loads data on mount). It is possible that I still need to wrap this in act and I am just confused about this update, but based on the conversation in https://github.com/bpb54321/dialog-app/pull/1#discussion_r308969946 my understanding is this this should work.

Reproduction:

https://codesandbox.io/embed/agitated-snyder-mvvgi

Most helpful comment

The test completes before the async request does, so setName is getting called and that's running outside of an act call. If you use one of React Testing Library's async utilities (which wrap act) to wait for the component to re-render then you'll be fine: https://codesandbox.io/s/condescending-pascal-m0qc0

>All comments

The test completes before the async request does, so setName is getting called and that's running outside of an act call. If you use one of React Testing Library's async utilities (which wrap act) to wait for the component to re-render then you'll be fine: https://codesandbox.io/s/condescending-pascal-m0qc0

Was this page helpful?
0 / 5 - 0 ratings