Test was not wrapped in act(...)
Asked Answered
C

1

8

I am running into a strange issue, would appreciate help here. I followed the example from here, can't tell what the heck is going on. The warning shouldn't be showing up, right?

Component: Hello.tsx

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

export default () => {
  const [loaded, setLoaded] = useState("false")

  useEffect(() => {
    async function load() {
      await Promise.resolve()
      setLoaded("true")
    }
    load()
  }, [])

  return loaded ? <div>loaded</div> : <div>loading...</div>
}

Test:

import { render } from "@testing-library/react"
import Hello from "./hello"

test("React Testing Library works!", () => {
  render(<Hello />)
})

The test passes, but I see a warning in the console:

Warning: An update to _default inside a test was not wrapped in act(...).
    
    When testing, code that causes React state updates should be wrapped into act(...):
    
    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */
    
    This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
        at _default (/Users/michael.kozakov/Snapchat/Dev/web/apps/bitmoji-studio/src/ui/routes/Edit/Sidebar/hello.tsx:4:31)

       7 |     async function load() {
       8 |       await Promise.resolve()
    >  9 |       setLoaded("true")
         |       ^
      10 |     }
      11 |     load()
      12 |   }, [])
Craw answered 1/4, 2022 at 3:49 Comment(0)
S
4

The test example in the codesandbox passes without warning. You forgot to use await screen.findByText(/loaded/i). The findBy Queries:

findBy methods are a combination of getBy queries and waitFor

findBy queries work when you expect an element to appear but the change to the DOM might not happen immediately.

For testing the async code, you need to wait for the state update to be applied. So you need to use waitFor or findBy queries.

findBy queries use waitFor underly, see makeFindQuery

Seibold answered 1/4, 2022 at 3:58 Comment(2)
This worked thanks! So was the warning happening because the result was not awaited anywhere in the test?Craw
@Craw See this answer. #71639588 and act() docSeibold

© 2022 - 2024 — McMap. All rights reserved.