我想测试在管道内完成的 3 个请求。简化示例:
httpClient.get<Data[]>(testUrl)
.pipe(
mergeMap(() => range(0, 2)),
mergeMap(() => httpClient.get<Data[]>(testUrl)),
)
我使用的是官方推荐:HttpTestingController。如果我一个接一个地收到请求,它可以正常工作httpTestingController.match
.但是,这不是我真正的应用程序的编写方式。它使用管道。
let testData: Data[] = [
{ name: 'bob' }, { name: 'carol' },
{ name: 'ted' }, { name: 'alice' }
];
// Make three requests in a row
httpClient.get<Data[]>(testUrl)
.subscribe(d => expect(d.length).toEqual(0, 'should have no data'));
httpClient.get<Data[]>(testUrl)
.subscribe(d => expect(d).toEqual([testData[0]], 'should be one element array'));
httpClient.get<Data[]>(testUrl)
.subscribe(d => expect(d).toEqual(testData, 'should be expected data'));
// get all pending requests that match the given URL
const requests = httpTestingController.match(testUrl);
expect(requests.length).toEqual(3);
// Respond to each request with different results
requests[0].flush([]);
requests[1].flush([testData[0]]);
requests[2].flush(testData);
如何使 httpTestingController.match 与管道内的多个 HTTP 请求一起工作?
这是我到目前为止尝试过的,这是可重现的示例:
httpClient.get<Data[]>(testUrl)
.pipe(
mergeMap(() => range(0, 2)),
mergeMap(() => httpClient.get<Data[]>(testUrl)),
)
.subscribe(d => expect(d.length).toEqual(0, 'should have no data'));
const requests = httpTestingController.match(testUrl);
console.log({requests}); // <--- why only one instead of 3??
requests[0].flush([]);
// requests[1].flush([]); // This is undefined. How do I flush the other two requests?
// requests[2].flush([]); // undefined.
// Error: Expected no open requests, found 2: GET /data, GET /data
https://stackblitz.com/edit/angular-http-testing2?file=src%2Ftesting%2Fhttp-client.spec.ts
文档说:
// get all pending requests that match the given URL
const requests = httpTestingController.match(testUrl);
所以你得到一个请求,因为只有一个待处理。当第一个请求完成时,其余将变为挂起状态。因此,要测试它,您需要一步一步地进行。
let sentCount = 1;
httpClient.get<Data[]>(testUrl)
.pipe(
mergeMap(() => range(0, 2)),
tap(() => sentCount++),
mergeMap(() => httpClient.get<Data[]>(testUrl)),
)
.subscribe(d => expect(d.length).toEqual(0, 'should have no data'));
const requests = httpTestingController.match(testUrl);
expect(sentCount).toBe(1);
requests[0].flush([]);
expect(sentCount).toBe(3);
httpTestingController.match(testUrl);