繁体   English   中英

如何测试是否从组件角度调用了服务

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

我有一个组件,它在初始化时从我的服务中调用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();

谁能帮我我在做什么错。

测试失败的原因是,您的组件间谍componentSpy实际上用空存根替换了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);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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