undefined
undefined

Reputation: 3632

How to test if a service is called from the component in angular

I have a component which on init calls getAllUsers() method and getAllUsers() calls getAllUsersApi from my service. I want to test if both the calls are actually made.

Here are some snippets from my code:

test.component.ts

ngOnInit(){
  this.getAllUsers();
}
getAllUsers(){
   this.userService.getAllUsersApi('');
}

test.service.ts

getAllUsersApi(){
   return this.http.get('api/endpoint')
}

test.service.spec.ts

it('should call getAllUsers method on init'){
  spyOn(userService, 'getAllUsersApi');
  spyOn(component, 'getAllUsers');
  component.ngOnInit();
  expect(component.getAllUsers).toHaveBeenCalled();
  expect(userService.getAllUsersApi).toHaveBeenCalled(); // it fails here
}

But it fails here: expect(userService.getAllUsersApi).toHaveBeenCalled();

Can anyone please help me what I am doing wrong.

Upvotes: 6

Views: 11468

Answers (1)

Fabian Küng
Fabian Küng

Reputation: 6183

The reason your test fails, is because your component spy componentSpy is actually replacing your getAllUsers function in your component with an empty stub and therefore your getAllUsersApi call will never happen. and.callThrough will set up a spy and make sure the original function is being called.

I would test it like this:

it('should call getAllUsers method on init', () => {
  // set up spies, could also call a fake method in case you don't want the API call to go through
  const userServiceSpy = spyOn(userService, 'getAllUsersApi').and.callThrough();
  const componentSpy = spyOn(component, 'getAllUsers').and.callThrough();

  // make sure they haven't been called yet
  expect(userServiceSpy).not.toHaveBeenCalled();
  expect(componentSpy).not.toHaveBeenCalled();

  // depending on how your component is set up, fixture.detectChanges() might be enough
  component.ngOnInit();

  expect(userServiceSpy).toHaveBeenCalledTimes(1);
  expect(componentSpy).toHaveBeenCalledTimes(1);
});

Upvotes: 15

Related Questions