Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting " No QueryClient set, use QueryClientProvider to set one " when testing a react query component with react testing library

I'm getting this error when testing a component that uses react query custom hook: " No QueryClient set, use QueryClientProvider to set one "

this is my hook:

export default () => {
  const loginMutation = useMutation(
    async (payload: LoginDto) => {
      return await MembershipService.login(payload);
    },
    {
      onSuccess: ({ data }: AxiosResponse) => alert(data),
      onError: (error: AxiosError) => {
        console.log(error);
      },
    }
  );

  const signupMutation = useMutation(
    async (payload: SignupDto) => {
      return await MembershipService.signup(payload);
    },
    {
      onSuccess: ({ data }: AxiosResponse) => alert(data),
      onError: (error: AxiosError) => {
        console.log(error);
      },
    }
  );

  return {
    loginMutation,
    signupMutation,
  };
};

and here is my test:

test("should display required error", async () => {
    render(
      <QueryClientProvider client={queryClient}>
        <Signup />
      </QueryClientProvider>
    );
    fireEvent.submit(screen.getByRole("button"));
    expect(await screen.findAllByRole("alert")).toHaveLength(5);
  });

As you can see, I already passed an instance of QueryClient class to wrapper component. And also I'm using axios and axios-mock-adaptor to mocking requests.

like image 867
Erfan Chegini Avatar asked Jun 27 '26 10:06

Erfan Chegini


1 Answers

For "react query" library use this

import { QueryClient, QueryClientProvider, useQuery } from 'react-query'
    const queryClient = new QueryClient()
    export default function App() {
   return (
     <QueryClientProvider client={queryClient}>
       <Example />
     </QueryClientProvider>
   )
}

But if you use '@tanstack/react-query' then

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';    
const queryClient = new QueryClient();
describe('Example page', () => {
<QueryClientProvider client={queryClient}>
          <Example />
        </QueryClientProvider>
});
like image 142
Alexandru Asaftei Avatar answered Jun 29 '26 22:06

Alexandru Asaftei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!