【问题标题】:Error testing external API function with jest (react-query: useQuery)用玩笑测试外部 API 函数时出错(react-query:useQuery)
【发布时间】:2021-03-06 21:01:41
【问题描述】:

使用 Jest 测试调用外部 API 的函数时,我收到一个错误,提示只能在功能组件内部使用挂钩。

我的函数(useGetGophys)使用来自react-queryuseQuery,这是钩子。

我希望能够开玩笑地测试 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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-09
      • 2021-04-27
      • 1970-01-01
      • 2019-01-04
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      相关资源
      最近更新 更多