Angular 测试 - 使用 rxjs switchMap 的链式 HTTP 请求 [英] Angular Testing - Chained HTTP Requests using rxjs switchMap
本文介绍了Angular 测试 - 使用 rxjs switchMap 的链式 HTTP 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在我的服务中对这个函数进行单元测试,该函数首先执行 POST 请求,然后执行 GET.我正在使用 switchMap 来完成此操作,但我遇到的问题是两个请求都没有被 HttpTestingController 匹配函数接收
I am trying to unit test this function in my service that first executes POST request and then executes a GET afterwards. I'm using switchMap to accomplish this but the problem I'm having is that both of the requests are not getting picked up the the HttpTestingController match function
这里是我要测试的服务功能:
Here is the service function I want to test:
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'))
);
}
这是该函数的规范:
describe('CowService', () => {
let cowService: CowService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule
]
});
cowService = TestBed.get(CowService);
httpMock = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
describe('save', () => {
const cowList: Cow[] = [
{ id: '1', name: 'Cow' },
{ id: '2', name: 'Another Cow' }
];
it('Successfully saves cow and updates the list of cows', () => {
const cow: Cow = { id: null, name: 'Third Cow' };
cowService.save(cow).subscribe();
const reqs = httpMock.match(request => request.url = '/api/cows');
console.log(reqs); // shows only the POST request and not the GET
expect(reqs[0].request.url).toEqual('/api/cows');
expect(reqs[0].request.method).toEqual('POST');
expect(reqs[1].request.url).toEqual('/api/cows');
expect(reqs[1].request.method).toEqual('GET');
reqs[0].flush({});
reqs[1].flush(cowList);
});
});
});
执行此操作时,我收到一条错误消息:
When doing this I get an error that says:
TypeError: 无法读取未定义的属性flush"
TypeError: Cannot read property 'flush' of undefined
推荐答案
尝试以下操作:
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);
});
这篇关于Angular 测试 - 使用 rxjs switchMap 的链式 HTTP 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文