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

Vue2 Composition API中Jest spyOn未检测到函数调用问题求助

Vue2 Composition API Jest测试:spy未捕获函数调用的问题及解决

问题原因

你遇到的问题核心在于:setup 内部的 closeReportModal 调用的是当前作用域内的原始 resetSearchDates 函数,而你通过 jest.spyOn(wrapper.vm, 'resetSearchDates') 监听的是 Vue 绑定到组件实例上的包装后的函数——这两个并不是同一个引用,所以 spy 无法捕获到内部调用。

控制台打印证明 resetSearchDates 确实执行了,但那是原始函数的执行,和你监听的 vm 上的函数无关。

解决方案

方案1:统一函数引用(推荐)

将相关函数放到一个 reactive 对象中,确保内部调用和暴露到组件实例的是同一个函数引用:

// 组件代码调整
export default defineComponent({
  name: 'PersonsReport',
  setup() {
    const isReportModalOpen = ref(false);

    // 用reactive包裹方法,确保引用一致
    const methods = reactive({
      resetSearchDates: () => {
        console.log('in resetSearchDates')
      },
      closeReportModal: () => {
        isReportModalOpen.value = false;
        // 调用同一个对象下的方法
        methods.resetSearchDates();
      }
    })

    return {
      ...methods,
      isReportModalOpen
    }
  }
})

调整后,原有测试代码即可正常工作:wrapper.vm.resetSearchDates 和 closeReportModal 内部调用的是同一个函数引用,spy 能正确捕获调用。

方案2:直接测试函数效果(无需spy)

如果不想修改组件代码,可放弃 spy,转而测试 resetSearchDates 执行后的实际效果。针对当前示例,可通过模拟 console.log 验证:

// 测试代码调整
test('closeReportModal to call resetSearchDates', async () => {
  const logSpy = jest.spyOn(console, 'log').mockImplementation();
  
  wrapper.vm.closeReportModal();
  await wrapper.vm.$nextTick();

  expect(logSpy).toHaveBeenCalledWith('in resetSearchDates');
  
  logSpy.mockRestore();
});

内容的提问来源于stack exchange,提问作者Sam Willis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 16:52:01