javascript - 用玩笑测试外部 API 函数时出错(react-query:useQuery)
问题描述
当使用 Jest 测试一个调用外部 API 的函数时,我收到一个错误,即只能在功能组件内部使用钩子。
我的函数(useGetGophys)使用useQuery
其中react-query
的钩子。
我希望能够开玩笑地测试 useGetGophy 吗?
我正在模拟实际的获取请求,如下面的测试文件代码所示。
使用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)
})
})
解决方案
您需要使用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);
});
推荐阅读
- django-models - 例外:保存 Django 数据模型时引发的 decimal.InvalidOperation
- java - appCtx 中的多个事务遇到 NoUniqueBeanDefinitionException
- html - SVG 子元素破坏了 HTML 网格布局
- testing - 测试更新用户配置文件数据
- sql - GROUP BY 查询后选择多个最大值
- c# - 实体框架从 MySQL 迁移到 SQL Server 并且表名缺少“dbo”
- javascript - 做出反应。聊天工具 API。MessageList 组件错误 - 呈现来自其他房间的消息。组件生命周期和状态
- javascript - 循环中的Javascript条件
- go - 通过字符在字符串中的位置获取字符
- javascript - Pagespeed 评分低 - 我错过了什么?