Angular unit test spyon

18 Views Asked by At

I have following service call in my ngOnInit() of component..

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

Here is the unit test for the same:-

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

But it is giving below error:-

Expected spy 'setAccounttype' to have been called.

Any idea?

1

There are 1 best solutions below

0
Rashmi Yadav On

Write your test case like this:

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

With this change, the spy should properly intercept the method call in your unit test. spyOn is a Jasmine testing function that allows you to spy on methods of objects and track their calls. It's commonly used in unit testing to verify that methods are being called with the expected arguments and to mock their behavior if needed.