query icon indicating copy to clipboard operation
query copied to clipboard

uneInfiniteQuery breaks in Jest without a call to result.isFetching

Open vezaynk opened this issue 3 years ago • 0 comments

Describe the bug

A call to result.isFetching seems to be required to make my test work. Accessors should not have side-effects of this kind.

Video of the issue: https://youtu.be/UpQccrG1Hm0

Code:

import { renderHook } from '@testing-library/react-hooks';
import makeWrapper from '../testUtils/makeWrapper';
import { withQueryClient } from '../services/queryClient';
import useQueryUntilEnd from './useQueryUntilEnd';
import { useInfiniteQuery } from '@tanstack/react-query';

describe("useQueryUntilEnd", () => {
    test("paginates correctly", async () => {

        const { result, waitForNextUpdate, waitFor, waitForValueToChange } = renderHook(() => {
            const result = useInfiniteQuery([], (params) => {
                console.log(">>>", params);
                return Math.random()
            }, {
                getNextPageParam(response,{length}) {
                    if (length < 5)
                        return Math.random().toString();
                }
            })
            const { isDone } = useQueryUntilEnd(result);
            return { isDone, result };
        }, {
            wrapper: makeWrapper(withQueryClient)
        });

        await waitFor(() => expect(result.current.isDone).toBeTruthy());
        
        expect(result.current.result.data?.pages.length).toBe(5);
    });
});
import { UseInfiniteQueryResult } from "@tanstack/react-query";
import { useEffect } from "react";

export default function useQueryUntilEnd(query: UseInfiniteQueryResult) {
    useEffect(() => {
        if (query.hasNextPage) {
            query.fetchNextPage();
        }
    }, [query]);

    const isDone = !query.hasNextPage && !query.isLoading;
    // This line looks like a no-op, but it is actually triggering a getter
    // Tests fail without this line
    query.isFetching;
    const isLoading = !isDone;
    return { isDone, isLoading }
}

Your minimal, reproducible example

its unit tests

Steps to reproduce

Try the code in jest

Expected behavior

Should not timeout

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

Jest

react-query version

Latest

TypeScript version

Latest

Additional context

No response

vezaynk avatar Aug 09 '22 03:08 vezaynk