Angular Тестирование - связанные HTTP-запросы с использованием rx js switchMap - PullRequest
1 голос
/ 24 марта 2020

Я пытаюсь выполнить модульное тестирование этой функции в моем сервисе, который сначала выполняет запрос POST, а затем выполняет GET. Я использую switchMap для выполнения sh этого, но проблема, с которой я сталкиваюсь, заключается в том, что оба запроса не обрабатываются функцией соответствия HttpTestingController

Вот сервисная функция, которую я хочу протестировать:

save(cow: Cow): Observable<Object> {
  return this.http.put<Cow>(`${this.cowUrl}/1`, cow, this.httpOptions)
    .pipe(switchMap(_ => {
       return this.getAllCows();
    })
  );
}

private getAllCows(): Observable<Cow[]> {
  return this.http.get<Cow[]>(`${this.cowUrl}`).pipe(tap(data => {
      this.cows = data;
    }),
    catchError(this.handleError<Cow[]>('getAllCows'))
  );
}

Вот значение c для этой функции:

describe('CowService', () => {
  let cowService: CowService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ]
    });

    cowService = TestBed.get(CowService);
    httpMock = TestBed.get(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();
  });

  describe('save', () => {
    const cowList: Cow[] = [
      { id: '1', name: 'Cow' },
      { id: '2', name: 'Another Cow' }
    ];
    it('Successfully saves cow and updates the list of cows', () => {
      const cow: Cow = { id: null, name: 'Third Cow' };

      cowService.save(cow).subscribe();

      const reqs = httpMock.match(request =>  request.url = '/api/cows');

      console.log(reqs); // shows only the POST request and not the GET

      expect(reqs[0].request.url).toEqual('/api/cows');
      expect(reqs[0].request.method).toEqual('POST');

      expect(reqs[1].request.url).toEqual('/api/cows');
      expect(reqs[1].request.method).toEqual('GET');

      reqs[0].flush({});
      reqs[1].flush(cowList);
    });
  });
});

При этом я получаю сообщение об ошибке:

TypeError: Не удается прочитать свойство 'flu sh' из неопределенного

1 Ответ

1 голос
/ 24 марта 2020

Попробуйте следующее:

    it('Successfully saves cow and updates the list of cows', () => {
      const cow: Cow = { id: null, name: 'Third Cow' };

      cowService.save(cow).subscribe(
        response => expect(response).toEqual(cowList);
      );

      const putCall = httpMock.expectOne('/api/cows');
      expect(putCall.request.method).toEqual('PUT');
      // flush what the put call should return
      putCall.flush({});

      const getCall = httpMock.expectOne('/api/cows');
      expect(getCall.request.method).toEqual('GET');
      // flush what the get call should return
      getCall.flush(cowList);
    });
...