模拟反应钩子返回的函数

Mocking a function returned by a react hook

我正在使用 useQuery 挂钩作为 React 中 Apollo Client 的一部分构建分页,它公开了一个名为 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 函数的最佳方法是什么?

一种方法就是模拟钩子

在您的规范文件中:

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'))
});
*/

您还可以模拟发生的事情 "behind the scenes" 来模拟网络错误,做任何您需要的事情来测试您的捕获。

编辑:

  1. this page 上搜索 __esModule: true,您就会明白。
  2. 模拟整个函数和 return 一切都作为模拟数据可能更容易。但是你可以unmock it使用真实的,以免与其他测试冲突。