
[英]How to check if a method from a service is called or not in Jasmine unit testing without using spyOn in Angular?
[英]Angular Jasmine Unit Testing: Mocking the results of a HTTP Request that is called in a service called from a component
大家好:我正在尝试为组件的更改编写一些单元测试,我们更改从服务返回对象的顺序。 我真的很想知道如何模拟 http 请求。 这些测试将用 karma/jasmine 编写,用于 angular
计划-component.ts
// this method is called in the constructor
getPlans() {
this.randomService.getRandomItems(this.id).subscribe(
(data: RandomItem[]) => {
this.activeItems = data.filter(e => e.isActive === true);
this.randomItems = data.filter(e => e.isActive === false);
this.loading = false;
},
(err: ResponseError) => { this.handleError(err); },
() => { this.loading = false; }
);
}
然后我们在文件中为 randomService 提供了这个 get 请求:
/* GET */
getRandomItems(id: string): Observable<RandomItem[] | ResponseError> {
return this.get<any>(`/items/${id}/getRandomItems`).pipe(
map(res => {
const activeItems: RandomItem[] = res.activeItem as RandomItem[];
const pendingItems: RandomItem[] = res.pendingItem as RandomItem[];
return activeItems.concat(pendingItems);
})
);
}
在我的规范中,我为plans-component.ts 构造函数的依赖项创建了间谍,并设法实例化了组件。 我介绍了一个间谍 randomSpy.getRandomItems.and.returnValue(of([]));
我想在测试组件时测试这个 getPlans 方法的结果,但我不知道如何模拟它在服务中调用的 http 请求的结果。 如果有人可以分享一些关于在哪里寻找建议的资源,那就太好了!
谢谢
既然你已经引入了一个间谍randomSpy.getRandomItems.and.returnValue(of([]));
, getRandomItems
应该返回这个。
尝试这样的事情:
it('should have one activeItems and one randomItems', () => {
// mock the response
randomSpy.getRandomItems.and.returnValue(of([{ isActive: true }, { isActive: false }]));
// call the method
component.getPlans();
// assert your expectations
expect(component.activeItems.length).toBe(1);
expect(component.randomItems.length).toBe(1);
});
这是学习 Angular 单元测试的一个很好的链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.