reactjs - 开玩笑窥探外部功能问题
问题描述
出于某种原因,我收到了这个错误:
Cannot spy the handleError property because it is not a function; undefined given instead
我正在使用间谍方法...
const spyHandleError = jest.spyOn(handleError, 'handleError');
...检查是否调用了 handleError 函数:
expect(spyHandleError).toHaveBeenCalled();
我的 handleError 函数如下所示:
import { reduxAction } from '../store/actions/auth';
export const handleError = (status, dispatch) => {
if(status === 403) {
return dispatch(reduxAction());
}
};
为什么我会收到这个错误,我该如何使用 spyOn 方法来测试它?
解决方案
当您调用jest.spyOn方法时,您必须提供包含您要监视的方法的对象作为第一个参数(文档)。
您可能正在导入handleError方法,例如:
import { handleError } from 'file-where-handle-error-is';
因此,您导入的handleError直接是函数,而不是包含函数的对象。
要解决您的问题,您可以导入handleError所在的模块,然后模拟handleError方法:
const utils = require('file-where-handle-error-is');
const spyHandleError = jest.spyOn(utils, 'handleError');
另一种解决方案是使用 jest.mock 模拟 handleError 所在的模块:
jest.mock('../../../src/utils/handle-error', () => {
return {
handleError: jest.fn()
};
推荐阅读
- html - 我想将我的卡附加到另一个 html 页面
- javascript - 无法在谷歌地球中呈现 kml 文件
- java - 如何从 java 程序中重新运行 java 代码?
- angularjs - AngularJs 如何使用 angular-jwt 从 $localStorage 获取 jwt 令牌
- magento - Akeneo - 导入产品 CSV - 导入错误 - 字段“sku”是预期的,提供的字段是
- linux - 如何找到正在运行的 Docker 容器的所有镜像标签?
- javascript - 每次显示一个输入时的表单输入问题(Vue)
- javascript - 来自网页的社交分享
- r - “如何在 R studio 中更改关键字颜色?”
- javascript - vue组件html不显示