![](/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.