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

Vue3+Vitest中使用wrapper.emitted获取自定义事件失败求助

解决Vitest中Vue3组件自定义事件无法捕获的问题

针对你的问题,这里有几个关键修复点:

1. 修正组件引用错误

你的测试代码中挂载的是InfoCard,但实际要测试的组件是button.vue(建议统一组件命名,比如改为Button)。挂载组件不匹配的话,根本无法捕获目标组件的事件。请确保挂载正确的组件:

// 导入正确的组件文件
import Button from './button.vue';

it("should emit an event when button is clicked", async () => {
  const wrapper = mount(Button, { // 改为挂载Button组件
    props: {
      buttonText: "Button text",
    },
  });
  // ... 后续测试逻辑
});

2. 移除手动触发的$emit

测试代码里手动调用wrapper.vm.$emit("onEventFired")完全没必要,这会干扰真实的按钮点击触发逻辑,不符合模拟用户操作的测试场景,直接删掉这行代码即可。

3. 优化事件断言逻辑

wrapper.emitted("onEventFired")返回的是事件触发记录的数组,每个元素对应一次事件的参数列表。可以通过断言数组存在且长度正确来验证事件是否触发:

修正后的完整测试代码

import { mount } from '@vue/test-utils';
import Button from './button.vue';

it("should emit an event when button is clicked", async () => {
  const wrapper = mount(Button, {
    props: {
      buttonText: "Button text",
    },
  });

  // 触发按钮点击
  await wrapper.find("button").trigger("click");

  // 断言事件已触发
  const emittedEvent = wrapper.emitted("onEventFired");
  expect(emittedEvent).toBeTruthy();
  // 进一步验证触发次数为1次
  expect(emittedEvent?.length).toBe(1);
});

额外检查项

  • 你的组件中defineEmits的类型定义是正确的,无需修改:
const emit = defineEmits<{
  (e: "onEventFired"): void;
}>();
  • 可以先断言按钮元素存在,确保选择器正确:expect(wrapper.find("button").exists()).toBe(true)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 11:12:34