Как тестировать связанные запросы с помощью 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


person Augustin Colesnic    schedule 25.03.2021    source источник


Ответы (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 и проверьте этот вопрос с ответом, это может помочь.

person AliF50    schedule 25.03.2021