测试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的解构结果中获取。
解决方案
- 从
@testing-library/react中单独导入waitFor - 移除
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
相关产品推荐
相关产品推荐

