spyOn服务/组件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已调用,这似乎很好。但是将它们组合为一个会抛出错误吗?

JB Nizet

当您侦查某个方法时,基本上是将其替换为不执行任何操作的方法(除了记录所进行的调用以便以后进行验证)。因此,伪组件函数不再执行任何操作,因此不再调用该服务。

您可以使用来使其实际执行操作

spyOn(component, "testFuncCall").and.callThrough();

请参阅说明文件

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章