模拟反应挂钩返回的函数

问题描述 投票:0回答:1

我在React中使用useQuery钩子作为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函数的最佳方法是什么?

javascript reactjs react-apollo apollo-client react-testing-library
1个回答
0
投票

[一种方法要做的只是模拟钩子

在您的规格文件中:

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

jest.mock('@apollo/react-hooks',() => ({
  __esModule:true
  default: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. __esModule: true上搜索this page,您会理解的。
  2. 仅模拟整个函数并将所有内容作为模拟数据返回可能更容易。但是您可以unmock it使用实际的,以便不与其他测试冲突。
© www.soinside.com 2019 - 2024. All rights reserved.