我试图模拟出在useQuery中包装的异步函数中的axios:
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.stubRequest('/some-url', {
status: 200,
response: fakeInputData,
})
useFetchWithQuery()
moxios.wait(function () {
done()
})但是我遇到了各种各样的问题,比如缺少上下文、存储等等,这些都是我在完全模仿过程中反复出现的。
发布于 2022-09-27 01:28:38
不要嘲笑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());https://stackoverflow.com/questions/73842840
复制相似问题