我遇到了一个奇怪的问题,希望能在这里得到帮助。我学习了这里的例子,不知道到底发生了什么。警告不应该出现对吧?
组件: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>
}测试:
import { render } from "@testing-library/react"
import Hello from "./hello"
test("React Testing Library works!", () => {
render(<Hello />)
})测试通过了,但我在控制台中看到了一个警告:
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 | }, [])发布于 2022-04-01 03:58:42
代码框中的测试示例在没有警告的情况下通过。你忘记使用await screen.findByText(/loaded/i)了。findBy查询:
findBy方法是getBy查询和waitForfindBy查询的组合,当您期望元素出现时,waitForfindBy查询可以工作,但对DOM的更改可能不会立即发生。
为了测试异步代码,您需要等待应用状态更新。因此,您需要使用waitFor或findBy查询。
findBy查询下面使用waitFor,请参阅makeFindQuery
https://stackoverflow.com/questions/71701591
复制相似问题