模拟反应挂钩返回的函数

时间:2020-03-06 17:02:40

标签: javascript reactjs react-apollo apollo-client react-testing-library

我正在使用useQuery钩子来建立分页,作为React中Apollo客户端的一部分,它公开了一个名为fetchMore的函数,如下所示:https://www.apollographql.com/docs/react/data/pagination/

一切正常,但是我尝试编写一种使用案例的测试,这是由于网络错误导致fetchMore函数失败的情况。我组件中的代码如下所示。

const App = () => {
// Some other component logic
  const {loading, data, error, fetchMore} = useQuery(QUERY)
  
  const handleChange = () => {
    fetchMore({
      variables: {
        offset: data.feed.length
      },
      updateQuery: (prev, { fetchMoreResult }) => {
        if (!fetchMoreResult) return prev;
        return Object.assign({}, prev, {
          feed: [...prev.feed, ...fetchMoreResult.feed]
        });
      }
    }).catch((e) => {
     // handle the error
    })
  }
}

基本上,我想测试fetchMore函数函数引发错误的情况。我不想模拟整个useQuery,只是fetchMore函数。在我的测试中仅模拟fetchMore函数的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

一种方法是仅模拟钩子

在您的规格文件中:

import { useQuery } from '@apollo/react-hooks'

jest.mock('@apollo/react-hooks',() => ({
  __esModule:true
  useQuery:jest.fn()
});

console.log(useQuery) // mock function - do whatever you want!

/*
 e.g. useQuery.mockImplementation(() => ({
  data:...
  loading:...
  fetchMore:jest.fn(() => throw new Error('bad'))
});
*/

您还可以模拟“幕后”发生的事情,以模拟网络错误,并执行所需的任何操作来测试捕获。

编辑:

  1. this page上搜索__esModule: true,您会理解的。
  2. 仅模拟整个函数并将所有内容作为模拟数据返回可能更容易。但是您可以unmock it使用真实的,以免与其他测试冲突。