我想测试在管道内完成的 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