【问题标题】:how to mock react-query useQuery in jest如何开玩笑地模拟 react-query useQuery
【发布时间】:2022-09-27 09:28:38
【问题描述】:

我试图模拟一个异步函数内部的 axios,该函数被包装在 useQuery 中:

import { useQuery, QueryKey } from \'react-query\'


export const fetchWithAxios = async () => {
   ... 
   ...
   ...
   const response = await someAxiosCall()
   ...
   return data
}

export const useFetchWithQuery = () => useQuery(key, fetchWithAxios, {
    refetchInterval: false,
    refetchOnReconnect: true,
    refetchOnWindowFocus: true,
    retry: 1,
  })

我想使用 moxios

  moxios.stubRequest(\'/some-url\', {
      status: 200,
      response: fakeInputData,
    })

    useFetchWithQuery()

    moxios.wait(function () {
      done()
    })

但是我遇到了各种缺少上下文、存储等问题,我很想完全模拟这些问题。

    标签: jestjs react-query


    【解决方案1】:

    不要嘲笑useQuery,嘲笑Axios!

    为了测试您对useQuery 的使用,您应该遵循的模式应该如下所示:

    const fetchWithAxios = (axios, ...parameters) => {
       const data = axios.someAxiosCall(parameters);
       return data;
    }
    export const useFetchWithQuery = (...parameters) => {
     const axios = useAxios();
     return useQuery(key, fetchWithAxios(axios, ...parameters), {
        // options
      })
    }
    

    useAxios 来自哪里?您需要编写上下文以通过应用程序传递 axios 实例。

    这将使您的测试最终看起来像这样:

    const { result, waitFor, waitForNextUpdate } = renderHook(() => useFetchWithQuery(..., {
       wrapper: makeWrapper(withQueryClient, withAxios(mockedAxios)),
    });
    await waitFor(() => expect(result.current.isFetching).toBeFalsy());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 2017-12-14
      • 2017-07-01
      • 1970-01-01
      • 2020-08-20
      • 2021-05-27
      • 2022-01-24
      相关资源
      最近更新 更多