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

Angular单元测试emit事件报Expected a spy, but got Function错误

Angular单元测试emit事件Spy报错修复方案

报错根因

Expected a spy, but got Function 错误本质是断言时的component.mychange.emit不是你提前注册的Spy对象,常见触发场景:

  • Spy注册完成后,component.mychange对应的EventEmitter实例被重新赋值,覆盖了绑定了Spy的旧实例
  • Input赋值后没有主动触发值变更事件,Angular值监听逻辑未执行,同时异步断言时机错误

修复代码

// 需提前从@angular/core/testing导入fakeAsync、tick
it('should change myComponent value', fakeAsync(() => {
  // 若mychange在ngOnInit中初始化,需先执行fixture.detectChanges()触发ngOnInit,再注册Spy
  spyOn(component.mychange, 'emit');
  const input = fixture.debugElement.query(By.css('#mychange')).nativeElement;
  
  // 赋值后主动触发input事件,触发绑定的逻辑
  input.value = "2";
  input.dispatchEvent(new Event('input'));
  
  // 触发变更检测
  fixture.detectChanges();
  // 处理异步队列
  tick();

  expect(component.mychange.emit).toHaveBeenCalledWith(2);
}));

额外排查项

  • 确认组件内mychange是通过@Output() mychange = new EventEmitter<number>();声明的,没有在业务逻辑或测试流程中被重新赋值
  • 若mychange是在ngOnInit等生命周期函数中初始化的,必须保证Spy注册操作在生命周期触发之后执行,避免新实例覆盖Spy绑定的旧实例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:24:04