12

Fix testing error for React Query component

 2 years ago
source link: https://muyexi.im/fix-testing-error-for-react-query-component/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Mar 14, 2023 1 min read

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

Published by:

</article


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK