reactjs - 确保在 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 方法,以便确保在我的笑话测试中调用它?
解决方案
您需要在呈现自定义挂钩时通过测试中的提供程序。您可以编写自己的提供程序函数或使用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
});
你可以在这里找到详细的解释
推荐阅读
- gradle - 如何在 gradle 中添加预处理任务
- wpf - WPF 将数据网格的值放入数据集中
- java - 使用流和 lambda 在 Java 8 中使用 if-else 条件
- r - 在 R 中拟合两个断点的分段回归:一条水平线、一条直线,然后又是一条水平线
- laravel - 如何解决错误“密码必须至少为八个字符并与确认匹配。” 在 laravel 5.8 中
- node.js - 何时将 React 与 npm 一起使用?
- html - 预先填写重定向表格
- pandas - 使用 pyplot 和 Seaborn 在同一图中绘制多个图
- docker - 为什么 print 不能与异步生成器一起正常工作?
- reactjs - Material-ui FormControlLabel 默认未选中