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

1

8

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.

Firstrate answered 2/3, 2022 at 8:43 Comment(3)
similar question, maybe you could find your answer here : #65590695Depriest
I got it while I was testing with jest and react-testing-library, and I did not have any issues during development or buildingFirstrate
duplicate of this one? #65694515 you're also not showing where the queryClient is created, and how the Signup component uses itNikos
G
0

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>
});
Goldsberry answered 17/5, 2024 at 8:6 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.