首页 > 解决方案 > 用玩笑测试外部 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)
    })
})

标签: javascriptreactjsjestjsreact-hooksreact-query

解决方案


您需要使用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);
});

推荐阅读