I'm facing a peculiar issue while testing my React components. When I use react-test-renderer in conjunction with react-query, my components don't seem to trigger a re-render after receiving data from an API response. This results in the component not displaying the fetched data.
However, when I switch to using @testing-library/react for testing, the components re-render as expected and display the data correctly. I'm using Mock Service Worker (MSW) to mock the API responses, and it seems to work fine with @testing-library/react.
Does anyone know why react-test-renderer might not trigger a re-render with react-query, and how to resolve this issue?
My component
import React from "react";
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
const fetchData = async () => {
const { data } = await axios.get("https://api.example.com/user");
console.log("fetchData", data);
return data;
};
const Example = () => {
const { data } = useQuery({
queryKey: ["repoData"],
queryFn: fetchData,
});
console.log("re-render", data);
return (
<div>
<h1>name: {data?.name}</h1>
</div>
);
};
import { render } from "@testing-library/react";
import React from "react";
import Example from "./Example";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { act, create } from "react-test-renderer";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});
const wrapper = () => (
<QueryClientProvider client={queryClient}>
<Example />
</QueryClientProvider>
);
const server = setupServer(
http.get("https://api.example.com/user", ({ request, params, cookies }) => {
return HttpResponse.json({
name: "mocked-react-query",
});
})
);
beforeEach(() => {
server.listen();
});
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
let tree
test("test react-test-renderer", async () => {
await act(async () => {
await create(wrapper());
});
await act(async () => {});
const h1 = await tree.root.findByType("h1");
expect(h1.props.children[1]).toEqual("mocked-react-query");
});
test("test @testing-library/react", async () => {
const result = render(wrapper());
expect(await result.findByText(/mocked-react-query/i)).not.toBeNull();
});
test with @testing-library/react enter image description here
test with react-test-renderer enter image description here
Environment: React version: 18.2.0 react-query version: 5.9.0 react-test-renderer version: 18.2.0 @testing-library/react version: 5.9.0 MSW version: 2.0.9
I expect that when using react-test-renderer for testing React components with react-query, the components should re-render upon receiving data from an API response