![](/img/trans.png)
[英]Angular unit test if component method is called according to a data from a service
[英]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.