首页 > 解决方案 > 确保在 Jest 中调用 React.useContext 中的函数

问题描述

给定一个如下所示的自定义钩子:

const getSavedInfo (id) => {
  const endpoint = getEndpoint(id)
  const {updateInfo} = React.useContext(infoContext)

  axios.get(endpoint).then((res) => {
   if (res) {
     updateInfo(res.data)
    }
  })
} 

我将如何正确模拟 updateInfo 方法,以便确保在我的笑话测试中调用它?

标签: reactjsaxiosjestjsmockingreact-hooks

解决方案


您需要在呈现自定义挂钩时通过测试中的提供程序。您可以编写自己的提供程序函数或使用react-hooks-testing-library它为您做同样的事情。像这样:

import { renderHook } from 'react-hooks-testing-library';

const wrapper = ({ children }) => (
  <InfoContext.Provider value={{updateInfo: jest.fn}}>{children}</InfoContext.Provider>
);


it('should call update info', () => {
  const { result } = renderHook(() => getSavedInfo(), { wrapper });
  
  // rest of the test code goes here
});

你可以在这里找到详细的解释


推荐阅读