You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

测试TanStack React Query:renderHook中waitFor非函数问题排查

解决React Query自定义Hook测试中“waitFor is not a function”错误

问题场景

测试React Query自定义Hook时触发waitFor is not a function错误,相关代码如下:

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook } from "@testing-library/react";
import { useCustomHookForTestCase } from "../useQueryCustomHook";
const queryClient = new QueryClient();

describe('Testing custom hooks of react query', () => {
    const wrapper = ({ children }) => (
        <QueryClientProvider client={queryClient}>
            {children}
        </QueryClientProvider>
    );

    it('Should get data of todos from api',async () => {
        const { result, waitFor } = await renderHook(() => useCustomHookForTestCase(), { wrapper });

        await waitFor(() => result.current.isSuccess );

        expect(result.current.data).toEqual("Hello");
    })
})

export function useCustomHookForTestCase() {
  return useQuery(['customHook'], () => 'Hello');
}

错误原因

waitFor是@testing-library/react提供的独立导出函数,并非renderHook方法的返回值,不能从renderHook的解构结果中获取。

解决方案

  1. 从@testing-library/react中单独导入waitFor
  2. 移除renderHook解构中的waitFor,直接使用导入的函数

修正后的完整代码:

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
// 新增waitFor的独立导入
import { renderHook, waitFor } from "@testing-library/react";
import { useCustomHookForTestCase } from "../useQueryCustomHook";
const queryClient = new QueryClient();

describe('Testing custom hooks of react query', () => {
    const wrapper = ({ children }) => (
        <QueryClientProvider client={queryClient}>
            {children}
        </QueryClientProvider>
    );

    it('Should get data of todos from api',async () => {
        // 仅解构renderHook返回的result
        const { result } = await renderHook(() => useCustomHookForTestCase(), { wrapper });

        await waitFor(() => result.current.isSuccess );

        expect(result.current.data).toEqual("Hello");
    })
})

export function useCustomHookForTestCase() {
  return useQuery(['customHook'], () => 'Hello');
}

内容的提问来源于stack exchange,提问作者Rohit Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:39:17