You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest测试嵌套函数点击事件报错:非Mock函数无法断言调用

解决Jest断言selectedItemFunc调用时报错的问题

这个报错的核心原因很明确:你试图断言的selectedItemFunc是原始普通函数,而Jest的toHaveBeenCalled()方法只能用于被它跟踪的mock函数或spy对象——Jest没法监控未被包装的普通函数的调用行为,所以才会抛出这个错误。下面是具体的解决步骤:

1. Mock目标函数

首先,你需要在测试文件里把selectedItemFunc替换成Jest的mock函数,让Jest能记录它的调用情况。假设你的函数是从./your-component-path(替换成实际的文件路径)导出的,在测试文件顶部添加以下代码:

import { selectedItemFunc } from './your-component-path';

// 仅mock selectedItemFunc,保留其他导出函数的原始实现
jest.mock('./your-component-path', () => ({
  ...jest.requireActual('./your-component-path'),
  selectedItemFunc: jest.fn(),
}));

这里用jest.requireActual是为了避免影响其他函数的正常功能,只针对我们要测试的selectedItemFunc做mock处理。

2. 调整测试用例

接下来修改你的测试代码,确保mock函数在每次测试前都是干净的,然后执行点击操作并断言调用:

it('should trigger selectedItemFunc when clicking an unchecked item', () => {
  // 清空mock函数的调用记录,避免其他测试用例的干扰
  selectedItemFunc.mockClear();

  const itemContainer = wrapper.find('.neighborhoodItemsContainer');
  itemContainer.simulate('click');

  // 断言函数被调用
  expect(selectedItemFunc).toHaveBeenCalled();
  
  // 可选:进一步验证调用参数是否符合预期
  expect(selectedItemFunc).toHaveBeenCalledWith(
    props.label,
    props.selectedItem,
    props.itemList[0],
    props.mapSelectedItems
  );
});

3. 优化组件的key(可选但推荐)

另外注意到你的组件里用了key={Math.random()},这会导致每次渲染时key都不一样,在测试中可能会出现查找元素不稳定的情况。建议换成固定的唯一值,比如item.value:

<div className="neighborhoodItemsContainer" key={item.value} onClick={...} >

这样调整后,你的测试应该就能正常断言selectedItemFunc的调用情况了。

内容的提问来源于stack exchange,提问作者Yasemin çidem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:04:38