Angular 如何测试是否从组件中调用服务

Angular 如何测试是否从组件中调用服务,angular,jasmine,karma-jasmine,Angular,Jasmine,Karma Jasmine,我有一个组件,它在init上调用getAllUsers()方法,getAllUsers()从我的服务中调用getAllUsersApi。我想测试一下这两个电话是否都打过 以下是我的代码中的一些片段: 测试组件.ts ngOnInit(){ this.getAllUsers(); } getAllUsers(){ this.userService.getAllUsersApi(''); } getAllUsersApi(){ return this.http.get('api/e

我有一个组件,它在init上调用getAllUsers()方法,getAllUsers()从我的服务中调用getAllUsersApi。我想测试一下这两个电话是否都打过

以下是我的代码中的一些片段:

测试组件.ts

ngOnInit(){
  this.getAllUsers();
}
getAllUsers(){
   this.userService.getAllUsersApi('');
}
getAllUsersApi(){
   return this.http.get('api/endpoint')
}
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
}
测试服务.ts

ngOnInit(){
  this.getAllUsers();
}
getAllUsers(){
   this.userService.getAllUsersApi('');
}
getAllUsersApi(){
   return this.http.get('api/endpoint')
}
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
}
测试服务规范ts

ngOnInit(){
  this.getAllUsers();
}
getAllUsers(){
   this.userService.getAllUsersApi('');
}
getAllUsersApi(){
   return this.http.get('api/endpoint')
}
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
}
但它在这里失败:
expect(userService.getAllUsersApi).toHaveBeenCalled()


谁能帮我一下我做错了什么。

您的测试失败的原因是您的组件spy
componentSpy
实际上正在用空存根替换组件中的
getAllUsers
函数,因此您的
getAllUsersApi
调用永远不会发生
和.callThrough
将设置间谍,并确保调用原始函数

我会这样测试它:

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

谢谢费边。这有帮助。