[英]spyOn service / component Angular2
我正在尝试通过服务实施单元测试。 我想澄清为什么它不起作用。
为我的规范类设置。
beforeEach(() => {
fixture = TestBed.createComponent(testComp);
service = fixture.debugElement.injector.get(TestService);
});
it('mockService', () => {
spyOn(service, "testFuncCall");
let buttonClick = fixture.debugElement.query(By.css('.testFuncCall'));
buttonClick.triggerEventHandler('click', null);
expect(service.testFuncCall).toHaveBeenCalled();
})
因此,上面的命令运行正常,如果我单击按钮-单击其他按钮,它将失败。 我当时想做的是
it('mockService', () => {
spyOn(service, "testFuncCall");
spyOn(component, "testFuncCall");
let buttonClick = fixture.debugElement.query(By.css('.testFuncCall'));
buttonClick.triggerEventHandler('click', null);
expect(component.testFuncCall).toHaveBeenCalled();
expect(service.testFuncCall).toHaveBeenCalled();
})
这将引发一个错误,提示已调用了预期的间谍testFuncCall。 只是想知道为什么会这样。 该组件具有一个称为testFuncCall的方法,该方法可启动按钮单击。 该方法将调用Service,该服务具有一个名为testFuncCall的方法。
如果我将其分开,一个用于测试是否已调用component.testFuncCall
,另一个用于是否已调用service.testFuncCall
,这似乎很好。 但是将它们组合为一个会抛出错误吗?
当您侦查某个方法时,基本上是将其替换为什么都不做的方法(除了记录所调用的记录,以便以后可以对其进行验证)。 因此,伪组件函数不再执行任何操作,因此不再调用该服务。
您可以使用来使其实际执行操作
spyOn(component, "testFuncCall").and.callThrough();
请参阅说明文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.