Angular Jasmine单元测试:模拟从组件调用的服务中调用的HTTP请求的结果



大家好:我正在尝试为一个组件的更改编写一些单元测试,其中我们更改了从服务返回对象的顺序。我真的很纠结如何模拟http请求。这些测试将在karma/jasmine中为angular

编写。plans-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);
})
);
}

在我的规范中,我为计划组件的依赖项创建了spy。并成功地实例化了该组件。我已经引入了一个间谍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单元测试的一个很好的链接。

最新更新