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

Jest/Vue Test Utils测试:b-modal作用域插槽close方法未定义触发click警告

解决方案

根因说明

你的推测完全正确,shallowMount默认生成的组件存根不会处理作用域插槽的参数传递,因此你从b-modal的modal-header作用域插槽中解构出来的close方法为undefined,绑定到点击事件后触发了Vue的运行时警告。

推荐方案:自定义b-modal存根并注入mock的close方法

这是最符合单元测试规范的方案,你不仅可以消除警告,还可以后续基于mock的close方法测试关闭按钮的交互逻辑,示例代码如下:

// 先定义mock的close方法,可用于后续断言调用情况
const mockClose = jest.fn()
return shallowMount(MyCustomParentComponent, {
    ...options,
    localVue,
    store,
    stubs: {
        // 替换默认的字符串存根为自定义存根组件
        'b-modal': {
            render(h) {
                // 渲染作用域插槽时主动传入close方法
                return h('div', this.$scopedSlots['modal-header']?.({ close: mockClose }))
            }
        }
    },
});

如果你的b-modal还用到了其他作用域插槽,只需要在自定义存根中对应补充插槽参数传递即可。

可选方案1:业务代码增加兜底逻辑

如果你不需要测试和b-modal相关的交互逻辑,也可以直接在业务代码中给点击事件加兜底,避免绑定undefined:

<button class="close close-profile text-dark" @click="close ?? () => {}">
    <i class="far fa-times" />
</button>

注意该方案需要修改业务代码,仅建议在确定生产环境下close方法一定会存在的场景下使用。

可选方案2:屏蔽特定警告(不推荐)

你也可以在Jest的全局初始化文件中配置屏蔽该特定警告,避免测试输出被污染:

const originalError = console.error
beforeAll(() => {
  console.error = (...args) => {
    if (/Invalid handler for event "click": got undefined/.test(args[0])) {
      return
    }
    originalError.apply(console, args)
  }
})

afterAll(() => {
  console.error = originalError
})

该方案会屏蔽所有同类警告,可能导致你漏掉真实存在的业务代码问题,非必要不建议使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 14:57:03