React 测试库 + React 查询 - 测试时承诺未得到解决

Psz*_*mko 5 javascript testing reactjs react-testing-library react-query

我正在使用 React 18、React 测试库 14.0.0 和 React Query 3.3。在浏览器(真实用户)上下文中,一切都像魅力一样工作。但在测试时我遇到了一些问题。

我的组件(简化):

import { useQuery } from "react-query"

export const Dashboard = () => {
    const { data } = useQuery(...)
    const { data: project } = useQuery(...)

return <div data-testid="project-name">{project.name}</div>
Run Code Online (Sandbox Code Playgroud)

考试:

import { ReactElement, Suspense } from "react"
import { render } from "@testing-library/react"
import { QueryClient } from "react-query"

export const testRenderer = (test: ReactElement) => 
render(<Suspense fallback={<div>loading...</div>}>
  <QueryClientProvider
    client={
      new QueryClient({
        defaultOptions: {
          queries: {
            suspense: true,
          },
        },
      })
    }
  >{test}</QueryClientProvider>
</Suspense>);

Run Code Online (Sandbox Code Playgroud)

考试:

import { waitFor } from "@testing-library/react";

test("render it", async () => {
  const { getByTestId } = testRenderer(<Dashboard />);

  await waitFor(async () => await findByTestId("project-name"));
  await waitFor(() => findByTestId("project-name"));
});
Run Code Online (Sandbox Code Playgroud)

结果,我在 waitFor 中看到FAIL Timed out。

<body>
  <div>
    <div>loading...</div>
  </div>
</body>
Run Code Online (Sandbox Code Playgroud)

因此很明显,<Suspense />在渲染真实的组件主体之前等待反应查询完成。

当我将 React 查询包装到 try/catch 中时,我看到的结果是console.log(error)Promise { <pending> }所以当我到达 时,承诺由于某种原因正在等待waitFor

我该如何修复它,甚至深入调试反应查询的问题?