I'm using React 18, React Testing Library 14.0.0, and React Query 3.3. Everything is working like a charm in the browser (real user) context. But while testing I am experiencing some problems.
My component (simplified):
import { useQuery } from "react-query"
export const Dashboard = () => {
const { data } = useQuery(...)
const { data: project } = useQuery(...)
return <div data-testid="project-name">{project.name}</div>
The test:
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>);
The test:
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"));
});
As a result, I see the FAIL Timed out in waitFor.:
<body>
<div>
<div>loading...</div>
</div>
</body>
So it's pretty apparent <Suspense />
is waiting for the react-queries to be finished before rendering the real component body.
When I wrap react queries into a try/catch I see as a result of console.log(error)
: Promise { <pending> }
so the promises are pending for some reason while I reach waitFor
.
How can I fix it or even debug deeply what's wrong with react-query?