首页 > 解决方案 > 开玩笑窥探外部功能问题

问题描述

出于某种原因,我收到了这个错误:

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 方法来测试它?

标签: reactjsjestjs

解决方案


当您调用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()
};

推荐阅读