当使用Jest测试一个调用外部API的函数时,我得到一个错误,它只能使用函数组件内部的钩子。
我的函数(UseGetGophys)使用来自react-query的useQuery,它是钩子。
我希望能够用jest测试useGetGophy?
我模拟了实际的fetch请求,可以在下面的测试文件代码中看到。

useGetGophy.js
import { useMemo } from 'react'
import { useQuery } from 'react-query'
import urlGenerator from "../utils/urlGenerator"
export default function useGetGophys({ query, limit }) {
const url = urlGenerator({ query, limit })
const { data, status } = useQuery(["gophys", { url }], async () => {
const res = await fetch(url)
return res.json()
})
return {
status,
data,
}
}测试文件useGetGophy.test.js
import useGetGophys from '../services/useGetGophys'
import { renderHook } from '@testing-library/react-hooks'
import { QueryClient, QueryClientProvider } from "react-query"
const desiredDataStructure = [{
id: expect.any(String),
images: {
fixed_width_downsampled: {
url: expect.any(String),
width: expect.any(String),
height: expect.any(String),
},
},
embed_url: expect.any(String),
bitly_gif_url: expect.any(String),
url: expect.any(String),
title: expect.any(String),
}]
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve(desiredDataStructure)
})
)
describe('getGetGophy - ', () => {
test('returns correctly structured data', async () => {
const gophys = useGetGophys('https://api.giphy.com/v1/gifs/trending?q=daniel&api_key=00000000&limit=15&rating=g')
expect(gophys).toBe(desiredDataStructure)
})
})发布于 2021-03-06 21:01:41
你需要使用testing-library/react-hooks来呈现你的钩子。只要您返回一个对象,就检查result.current.data,如下所示:
import { renderHook } from '@testing-library/react-hooks';
test('returns correctly structured data', () => {
const { result } = renderHook(() => useGetGophys('yourUrl'));
expect(result.current.data).toEqual(desiredDataStructure);
});https://stackoverflow.com/questions/66505876
复制相似问题