2

I've a custom React hook which uses react-query useQuery() in it-self:

const useFetchSomething = () => {
  const { data, isLoading } = useQuery('key', ....);
  return .......
}

I had to create a custom hook then use the useQuery() hook inside it, because it has some features and gets data from react-query!

I tried to test this hook with react-hooks-testing-library:

const { result } = renderHook(() => useFetchSomething());

but I get this error:

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

for this, how can I wrap this part: renderHook(() => useFetchSomething()) with Provider?

1 Answer 1

12

renderHook accepts options, and one of them is the wrapper component, where you can specify a react component to wrap the test component in when rendering. This is a good place to put providers.

const createWrapper = () => {
  const queryClient = new QueryClient()
  return ({ children }) => (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  )
}

const { result } = renderHook(() => useFetchSomething(), {
  wrapper: createWrapper()
});

I have an in-depth guide to testing react query in my blog.

Sign up to request clarification or add additional context in comments.

1 Comment

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.