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

如何测试Vue 3组合式函数是否触发正确的事件?

测试Vue 3组合式函数的事件触发与负载验证

测试思路

通过模拟emit函数追踪调用行为,就能验证事件是否被正确触发,以及负载数据是否符合预期。Vitest自带的vi.fn()可以创建模拟函数,用来记录调用次数、传入参数等关键信息。

完整测试代码(TypeScript版)

import { describe, it, expect, vi } from 'vitest';
import { useDemo } from './useDemo';

describe('useDemo', () => {
  it('调用demoFunction时应触发携带正确负载的customEvent', () => {
    // 创建模拟的emit函数
    const mockEmit = vi.fn();
    // 传入模拟emit,获取组合式函数返回的方法
    const { demoFunction } = useDemo(mockEmit);

    // 执行待测试的函数
    demoFunction();

    // 验证emit的调用情况
    expect(mockEmit).toHaveBeenCalledOnce();
    expect(mockEmit).toHaveBeenCalledWith('customEvent', 42);
  });
});

关键步骤说明

  • 用vi.fn()生成mockEmit模拟函数,它会自动记录所有调用细节。
  • 调用useDemo并传入mockEmit,拿到要测试的demoFunction。
  • 执行demoFunction后,通过Vitest断言验证:
    • toHaveBeenCalledOnce():确保事件只被触发一次。
    • toHaveBeenCalledWith('customEvent', 42):确保事件名和负载数据完全符合预期。

JavaScript版适配代码

如果项目使用纯JavaScript,去掉类型相关代码即可,测试逻辑完全一致:

import { describe, it, expect, vi } from 'vitest';
import { useDemo } from './useDemo';

describe('useDemo', () => {
  it('调用demoFunction时应触发携带正确负载的customEvent', () => {
    const mockEmit = vi.fn();
    const { demoFunction } = useDemo(mockEmit);

    demoFunction();

    expect(mockEmit).toHaveBeenCalledOnce();
    expect(mockEmit).toHaveBeenCalledWith('customEvent', 42);
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 05:23:10