0

我正在使用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在我的测试中模拟函数的最佳方法是什么?

4

1 回答 1

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. __esModule: true这个页面上搜索你就会明白。
  2. 模拟整个函数并将所有内容作为模拟数据返回可能更容易。但是您可以取消模拟它以使用真实的,以免与其他测试冲突。
于 2020-03-06T17:14:21.020 回答