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.

3
  • similar question, maybe you could find your answer here : stackoverflow.com/questions/65590195/… Commented Mar 2, 2022 at 9:25
  • 1
    I got it while I was testing with jest and react-testing-library, and I did not have any issues during development or building Commented Mar 2, 2022 at 9:39
  • duplicate of this one? stackoverflow.com/questions/65694015/… you're also not showing where the queryClient is created, and how the Signup component uses it Commented Mar 3, 2022 at 19:28

1 Answer 1

6

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>
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.