简体   繁体   中英

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.

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM