Angular - 为 switchMap 编写单元测试用例
Angular - Writing unit test case for switchMap
以下是我的两种服务方式
getCountries(offset: number) {
let url = this.configManagerService.countriesApiUrl;
const httpHeaders = this.getHeaders();
return this.httpClient.get(url + offset, { headers: httpHeaders });
}
getAllCountries(offset: number = 0, resultOld: any[] = []) {
return this.getCountries(offset).pipe(
//not getting covered
switchMap((result: any) => {
offset = result.length > 0 ? offset + result.length : -1;
return offset >= 0
? this.getAllCountries(offset, [...resultOld, ...result])
: of(resultOld);
//not getting covered
})
);
}
我能够编写涵盖 getCountries
功能的单元测试用例,但无法理解如何涵盖我在关于 switchMap
的评论中提到的代码。尝试 google 它但无法找到适合我要求的任何内容。这里的任何帮助将不胜感激。谢谢
这是一个例子。
it('returns resultOld if result length is zero', (done: DoneFn) => {
const resultOld = [];
spyOn(service, 'getCountries').and.returnValue(of(resultOld));
service.getAllCountries(2, resultOld).subscribe(results => {
expect(results.length).toBe(0);
done();
});
});
it('calls getAllCountries over and over until converge', (done: DoneFn) => {
const resultOld = [{ name: 'USA' }];
spyOn(service, 'getCountries').and.returnValue(of(resultOld));
service.getAllCountries(-1, resultOld).subscribe(results => {
expect(results.length).toBe(1);
done();
});
});
以下是我的两种服务方式
getCountries(offset: number) {
let url = this.configManagerService.countriesApiUrl;
const httpHeaders = this.getHeaders();
return this.httpClient.get(url + offset, { headers: httpHeaders });
}
getAllCountries(offset: number = 0, resultOld: any[] = []) {
return this.getCountries(offset).pipe(
//not getting covered
switchMap((result: any) => {
offset = result.length > 0 ? offset + result.length : -1;
return offset >= 0
? this.getAllCountries(offset, [...resultOld, ...result])
: of(resultOld);
//not getting covered
})
);
}
我能够编写涵盖 getCountries
功能的单元测试用例,但无法理解如何涵盖我在关于 switchMap
的评论中提到的代码。尝试 google 它但无法找到适合我要求的任何内容。这里的任何帮助将不胜感激。谢谢
这是一个例子。
it('returns resultOld if result length is zero', (done: DoneFn) => {
const resultOld = [];
spyOn(service, 'getCountries').and.returnValue(of(resultOld));
service.getAllCountries(2, resultOld).subscribe(results => {
expect(results.length).toBe(0);
done();
});
});
it('calls getAllCountries over and over until converge', (done: DoneFn) => {
const resultOld = [{ name: 'USA' }];
spyOn(service, 'getCountries').and.returnValue(of(resultOld));
service.getAllCountries(-1, resultOld).subscribe(results => {
expect(results.length).toBe(1);
done();
});
});