1

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

4

1 回答 1

2

文档说:

// get all pending requests that match the given URL
const requests = httpTestingController.match(testUrl);

因此,您收到一个请求,因为只有一个未决。当第一个请求完成时,Rest 将变为挂起状态。所以要测试它,你要一步一步来。

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);
于 2020-06-25T00:22:46.893 回答