我的组件 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.
有什么想法吗?
像这样编写你的测试用例:
it('should call the method', () => {
const accountServiceSpy = spyOn(accountTypeService, 'SetAccountType');
component.ngOnInit();
expect(accountServiceSpy).toHaveBeenCalled();
}
通过此更改,间谍应该正确拦截单元测试中的方法调用。 pyOn 是一个 Jasmine 测试函数,允许您监视对象的方法并跟踪它们的调用。它通常用于单元测试中,以验证是否使用预期参数调用方法,并在需要时模拟它们的行为。