我有一个组件,该组件在初始化时会从我的服务中调用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();
任何人都可以帮我做错什么事。
答案 0 :(得分: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);
});