角度单元测试间谍

问题描述 投票:0回答:1

我的组件 ngOnInit() 中有以下服务调用..

ngOnInit(){
 this.accountTypeService.SetAccountType(AccountTypeEnum.Savings);
}

这是相同的单元测试:-

it('should call the method', () => {
  spyOn(accountTypeService, 'setAccountType');
  component.ngOnInit();
  expect(accountTypeService.setAccounttype).toHaveBeenCalled();
}

但它给出以下错误:-

Expected spy 'setAccounttype' to have been called.

有什么想法吗?

angular typescript jasmine
1个回答
0
投票

像这样编写你的测试用例:

it('should call the method', () => {
  const accountServiceSpy = spyOn(accountTypeService, 'SetAccountType');
  component.ngOnInit();
  expect(accountServiceSpy).toHaveBeenCalled();
}

通过此更改,间谍应该正确拦截单元测试中的方法调用。 pyOn 是一个 Jasmine 测试函数,允许您监视对象的方法并跟踪它们的调用。它通常用于单元测试中,以验证是否使用预期参数调用方法,并在需要时模拟它们的行为。

© www.soinside.com 2019 - 2024. All rights reserved.