问题描述
我需要复制为事件调用的间谍的功能。即,假设存在:spyOn(method).and.callThrough()
,是否还存在类似:spyOnEvent(event).and.triggerThrough()
?
解决方法
该事件的作用类似于函数调用,因此您可以以相同的方式对其进行设置。
例如当您设置组件并拥有一个函数 (onInit
) 时,您希望在其中调用另一个函数 (myFunction
) 作为其中的一部分。
// arrange
spyOn(component,'myFunction');
// act
component.onInit();
// assert
expect(component.myFunction).toHaveBeenCalled();
以同样的方式,您可以设置您的事件,其中事件 (myEvent
) 在测试函数 (myFunction
) 内触发:
// arrange
spyOn(component.myEvent,'emit');
// act
component.myFunction();
// assert
expect(component.myEvent.emit).toHaveBeenCalled();
只有当您的服务具有预期执行的调用时,您才会正常设置数据,因为您的测试范围需要一些返回数据:
spyOn(myService,'myServiceFunction').and.returnValue(of(true));
或者您可以将其设置为:
mockedService.spyOf(x => x.myServiceFunction).and.returnValue(of(true));