如何测试是否以角度方式从组件调用服务

问题描述 投票:0回答:1

我有一个组件,在init调用getAllUsers()方法和getAllUsers()从我的服务调用getAllUsersApi。我想测试两个调用是否实际完成。

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

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
}

但它失败了:expect(userService.getAllUsersApi).toHaveBeenCalled();

任何人都可以帮助我,我做错了什么。

angular jasmine karma-jasmine
1个回答
1
投票

您的测试失败的原因是因为您的组件间谍componentSpy实际上正在使用空存根替换组件中的getAllUsers函数,因此您的getAllUsersApi调用将永远不会发生。 and.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);
});
© www.soinside.com 2019 - 2024. All rights reserved.