Fix testing error for React Query component

Original link: https://muyexi.im/fix-testing-error-for-react-query-component/

 import { useQuery, useQueryClient } from "react-query"; export default function Home() { const queryClient = useQueryClient(); return <div></div>; } import { screen, render } from '@testing-library/react'; test('home', () => { render(<Home/>); });

If you’re testing your React component with Jest and React Testing Library, and the component is using React Query , you may come across this test error:

Error: Uncaught [Error: No QueryClient set, use QueryClientProvider to set one]

To fix, use renderWithClient to wrap your component in a QueryClientProvider :

 import React from 'react'; import { render } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from 'react-query'; export function renderWithClient(client: QueryClient, ui: React.ReactElement) { const { rerender, ...result } = render( <QueryClientProvider client={client}>{ui}</QueryClientProvider> ); return { ...result, rerender: (rerenderUi: React.ReactElement) => rerender( <QueryClientProvider client={client}>{rerenderUi}</QueryClientProvider> ), }; }

Source: TanStack/query .

This article is transferred from: https://muyexi.im/fix-testing-error-for-react-query-component/
This site is only for collection, and the copyright belongs to the original author.