测试未包含在 act(...) 中

ind*_*man 6 reactjs jestjs react-testing-library

我遇到了一个奇怪的问题,非常感谢这里的帮助。我按照这里的例子,不知道到底发生了什么。警告不应该出现,对吧?

组件: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>
}
Run Code Online (Sandbox Code Playgroud)

测试:

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

test("React Testing Library works!", () => {
  render(<Hello />)
})
Run Code Online (Sandbox Code Playgroud)

测试通过,但我在控制台中看到警告:

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 |   }, [])
Run Code Online (Sandbox Code Playgroud)

sli*_*wp2 3

codesandbox 中的测试示例在没有警告的情况下通过。你忘了使用await screen.findByText(/loaded/i). 按查询查找

findBygetBy方法是查询和方法的组合waitFor

findBy当您期望出现某个元素但 DOM 的更改可能不会立即发生时,查询就会起作用。

为了测试异步代码,您需要等待应用状态更新。所以需要使用waitFororfindBy查询。

findBy查询使用waitForunderly,参见makeFindQuery