Why doesn't react-query produce a value in my Jest test?

Viewed 99

I believe I followed the docs in how I implementing the test, and yet it fails due a timeout.

It always says it is loading, but the function is returning immediately (whether it returns a promise or a value seems to not make a difference).

import React from 'react';

import { useInfiniteQuery, QueryClientProvider, QueryClient, useQuery } from '@tanstack/react-query' 
import { renderHook, act } from '@testing-library/react-hooks'

function useCustomInfinuteHook() { // Not using this, but it doesn't work either
    return useInfiniteQuery([], () => {
        return Math.random();
    }, {
        getNextPageParam() {
            return 2
        }
    }) 
}
export function useCustomHook() {
    return useQuery(['customHook'], async () => Promise.resolve('Hello'));
  }

  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        // āœ… turns retries off
        retry: false,
      },
    },
  })
const wrapper = ({ children }: any) => (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  );
  
  
test("React Query?", async () => {
    const { result: { current }, waitForValueToChange, waitForNextUpdate } = renderHook(() => useCustomHook(), {
        // Wraps hook in a react-query provider
        wrapper
    })
    
    expect(current.isLoading).toBeTruthy();
    await waitForValueToChange(() => current.isLoading, { timeout: 10000}); // Throws error due to timeout
    expect(current.isLoading).toBeFalsy();
}, 10000)

Outputs:

ā— React Query?

    thrown: "Exceeded timeout of 10000 ms for a test.
    Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."

      32 |   
      33 |   
    > 34 | test("React Query?", async () => {
         | ^
      35 |     const { result: { current }, waitForValueToChange } = renderHook(() => useCustomHook(), {
      36 |         // Wraps hook in a react-query provider
      37 |         wrapper

      at Object.<anonymous> (src/queries/testquery.test.tsx:34:1)
1 Answers

Turns out the issue was destructuring result. The current accessor must be accessed as a property of result.

Related