【发布时间】:2021-03-06 21:01:41
【问题描述】:
使用 Jest 测试调用外部 API 的函数时,我收到一个错误,提示只能在功能组件内部使用挂钩。
我的函数(useGetGophys)使用来自react-query 的useQuery,这是钩子。
我希望能够开玩笑地测试 useGetGophy 吗?
我正在模拟实际的 fetch 请求,如下面的测试文件代码所示。
使用GetGophy.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,
}
}
测试文件 使用GetGophy.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)
})
})
【问题讨论】:
标签: javascript reactjs jestjs react-hooks react-query