【问题标题】:On emit event: Expected a spy, but got Function在发出事件时:期望一个间谍,但得到了函数
【发布时间】:2021-11-15 09:08:03
【问题描述】:

我运行了这个测试,但我得到了这个错误:

Unhandled Promise rejection: <toHaveBeenCalledWith> : Expected a spy, but got Function.

  it('should change myComponent value', () => {
     spyOn(component.mychange, 'emit');
     const input = fixture.debugElement.query(By.css('#mychange')).nativeElement;
     input.value = "2";
     fixture.whenStable().then(() => {
       expect(component.mychange.emit).toHaveBeenCalledWith(2);
     });
   });

有类似的问题,但是在发出事件时发生在我身上,我尝试了这些问题的解决方案,但它们不起作用。

【问题讨论】:

  • 如果你将 spyOn 分配给一个变量并在稳定时使用它会发生什么?
  • 错误:预期的间谍发射已被调用:[ 2 ],但从未调用过。

标签: angular unit-testing testing karma-jasmine


【解决方案1】:

看到你在这里设置了一个 spy on emit 方法 - spyOn(component.mychange, 'emit');

问题似乎在于触发更改 -

所以你需要调用 component.mychange(10);

所以你的代码会变成

it('should change myComponent value', async () => {
     spyOn(component.mychange, 'emit');
     const input = fixture.debugElement.query(By.css('#mychange')).nativeElement;
     input.value = "2";
     component.mychange(2);
     await fixture.whenStable()
     expect(component.mychange.emit).toHaveBeenCalledWith(2);
   });

还请我使用 async await 让它变得更好!

【讨论】:

  • 你是对的,但是那个发射直接发生在 HTML 中,它没有包装在一个函数中,所以在这一点上我真的想知道这个测试是否正确......我猜它只是没有不必。
  • 好的。只是考虑了一下。您必须删除 component.mychange(2);并调用 input.dispatchEvent(new Event('input'));可以试试吗?
猜你喜欢
  • 2020-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-13
  • 2022-12-12
  • 2022-11-11
  • 1970-01-01
相关资源
最近更新 更多