Angular 角度测试-使用rxjs switchMap链接HTTP请求
我试图在我的服务中对这个函数进行单元测试,它首先执行POST请求,然后执行GET。我正在使用switchMap来完成这项工作,但我遇到的问题是,这两个请求都没有通过HttpTestingController匹配函数获取 下面是我要测试的服务功能:Angular 角度测试-使用rxjs switchMap链接HTTP请求,angular,unit-testing,jasmine,karma-jasmine,angular8,Angular,Unit Testing,Jasmine,Karma Jasmine,Angular8,我试图在我的服务中对这个函数进行单元测试,它首先执行POST请求,然后执行GET。我正在使用switchMap来完成这项工作,但我遇到的问题是,这两个请求都没有通过HttpTestingController匹配函数获取 下面是我要测试的服务功能: save(cow: Cow): Observable<Object> { return this.http.put<Cow>(`${this.cowUrl}/1`, cow, this.httpOptions) .p
save(cow: Cow): Observable<Object> {
return this.http.put<Cow>(`${this.cowUrl}/1`, cow, this.httpOptions)
.pipe(switchMap(_ => {
return this.getAllCows();
})
);
}
private getAllCows(): Observable<Cow[]> {
return this.http.get<Cow[]>(`${this.cowUrl}`).pipe(tap(data => {
this.cows = data;
}),
catchError(this.handleError<Cow[]>('getAllCows'))
);
}
执行此操作时,我会收到一个错误,上面显示:
TypeError:无法读取未定义的属性“flush”
请尝试以下操作:
it('Successfully saves cow and updates the list of cows', () => {
const cow: Cow = { id: null, name: 'Third Cow' };
cowService.save(cow).subscribe(
response => expect(response).toEqual(cowList);
);
const putCall = httpMock.expectOne('/api/cows');
expect(putCall.request.method).toEqual('PUT');
// flush what the put call should return
putCall.flush({});
const getCall = httpMock.expectOne('/api/cows');
expect(getCall.request.method).toEqual('GET');
// flush what the get call should return
getCall.flush(cowList);
});
addCow
callsave
?很抱歉,我更新了问题以反映正确的函数名称您的刷新顺序似乎有误。从一个呼叫跳到另一个呼叫,你进行你的呼叫,做你的期望/匹配,刷新,然后重复下一个呼叫的过程,最终调用验证,这确保你没有悬空的HTTP呼叫(所以你知道你完成了你的序列)。我明确地没有考虑在这种情况下的操作顺序。根据你的建议和@50条建议,它开始工作了!我尝试了一个更早的变化,但绝对没有考虑预期和冲洗的顺序。谢谢这只有在顺序请求的方法不同时才有效,对吗?没错,但我认为您可以使用match
helper来匹配所有请求。
it('Successfully saves cow and updates the list of cows', () => {
const cow: Cow = { id: null, name: 'Third Cow' };
cowService.save(cow).subscribe(
response => expect(response).toEqual(cowList);
);
const putCall = httpMock.expectOne('/api/cows');
expect(putCall.request.method).toEqual('PUT');
// flush what the put call should return
putCall.flush({});
const getCall = httpMock.expectOne('/api/cows');
expect(getCall.request.method).toEqual('GET');
// flush what the get call should return
getCall.flush(cowList);
});