首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用jest测试外部API函数时出错(react-query: useQuery)

使用jest测试外部API函数时出错(react-query: useQuery)
EN

Stack Overflow用户
提问于 2021-03-06 20:56:34
回答 1查看 644关注 0票数 0

当使用Jest测试一个调用外部API的函数时,我得到一个错误,它只能使用函数组件内部的钩子。

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

我希望能够用jest测试useGetGophy?

我模拟了实际的fetch请求,可以在下面的测试文件代码中看到。

useGetGophy.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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)
    })
})
EN

回答 1

Stack Overflow用户

发布于 2021-03-06 21:01:41

你需要使用testing-library/react-hooks来呈现你的钩子。只要您返回一个对象,就检查result.current.data,如下所示:

代码语言:javascript
复制
import { renderHook } from '@testing-library/react-hooks';

test('returns correctly structured data', () => {
  const { result } = renderHook(() => useGetGophys('yourUrl'));
  expect(result.current.data).toEqual(desiredDataStructure);
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66505876

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档