2

如何在链式请求中对 mergeMap 进行单元测试,例如以下服务中的请求:

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { mergeMap, delay } from "rxjs/operators";

@Injectable({
  providedIn: "root"
})
export class reqService {
  constructor(private httpClient: HttpClient) {}

  getMultimpleReq() {
    return this.httpClient.get(`https://swapi.dev/api/starships/9/`).pipe(
      mergeMap(obj => {
        console.log("first request", obj);
        let filmFromFirstRequest = obj.MGLT;
        return this.httpClient
          .get(`https://swapi.dev/api/people/${filmFromFirstRequest}/`)
          .pipe(delay(1000));
      })
    );
  }
}

这是https://stackblitz.com/edit/angular-chainrequests?devtoolsheight=33&file=src/app/reqservice.ts上的完整应用示例代码

4

1 回答 1

1

你必须使用HttpTestingController,试试这个:

// httpMock is HttpTestingController below.
// we need fakeAsync because you have a delay and we need to traverse the time in a fake way
// We don't want to wait for the whole 1 second
it('makes subsequent api calls', fakeAsync(() => {
  const getCallResponse = { MGLT: 'xyz' }; // mock your get call
  const secondGetCallResponse = {}; // mock your second get call
  let finalResponse: any;
  // subscribe to the method to send the http requests to take flight
  const httpSubscription = reqService.getMultimpleReq().subscribe(
    response => finalResponse = response;
  );
  
  // resolve the first get response
  const getCall = httpMock.expectOne('https://swapi.dev/api/starships/9/');
  expect(getCall.request.method).toEqual('GET');
  // we flush this response
  getCall.flush(getCallResponse);
  // xyz in the url because we made MGLT to 'xyz'
  const secondGetCall = httpMock.expectOne('https://swapi.dev/api/people/xyz/');
  expect(getCall.request.method).toEqual('GET');
  secondGetCall.flush(secondGetCallResponse);
  
  tick(1001); // advance the timer by 1001 ms to ensure the subscribe runs
  expect(finalResponse).toEqual(secondGetCallResponse); // your final assertion
  
});

检查这个以测试 HTTP 调用并检查这个问题并给出答案,它可能会有所帮助。

于 2021-03-25T19:26:07.483 回答