Как я могу модульное тестирование этой функции, которая обрабатывает наблюдаемые - PullRequest
0 голосов
/ 20 апреля 2020

Я создал эту функцию, потому что для всех запросов, которые мое приложение отправляет с использованием http.post, именно так разные части обрабатывают ответ. Поэтому вместо того, чтобы дублировать код, я подумал создать функцию. Но я не могу понять, как выполнить модульное тестирование этой функции.

private editAnswerSubject: Subject<Result>;
subscribeToReturnedObservable(observable:Observable<any>, subject:Subject<Result>) {
    observable.subscribe((res) => {
        const ev = <HttpEvent<any>>(res);
        if (ev.type === HttpEventType.Response) {
          const isResponseStructureOK: boolean = this.helper.validateServerResponseStructure(ev.body);
          if (isResponseStructureOK) {
            const response: ServerResponseAPI = ev.body;
            subject.next(new Result(response.result, response['additional-info']));

          } else {
            subject.next(new Result(messages.error, messages.invalidStructureOfResponse));
          }
        }
      },
      (error: ServerResponseAPI) => {
        const errorMessage: string = this.helper.userFriendlyErrorMessage(error);
        subject.next(new Result(messages.error, errorMessage));    
      },
      () => { // observable complete
      });
  }

  editAnswer(answer: Answer): any {
    const observable = this.bs.editAnswer(answer)
    this.subscribeToReturnedObservable(observable,this.editAnswerSubject);
  }

Тест, который я написал до сих пор:

  describe('subscribeToReturnedObservable tests:', () => {
    beforeEach(() => {
      TestBed.configureTestingModule({
        imports: [HttpClientTestingModule],
        providers: [QuestionManagementService, HelperService, WebToBackendInterfaceService, AuthService, HttpClient, HttpHandler]
      });
    });

fit('should call send next value for the subject is the response from the server is ok', () => {
  const questionService:QuestionManagementService = TestBed.get(QuestionManagementService);
  const body = {"result":"success", "additional-info":"some additional info"};
  const receivedHttpEvent = new HttpResponse({body:body});
  let observable = new Observable();
  spyOn(observable,'subscribe').and.returnValue(receivedHttpEvent);
  spyOn(questionService['editQuestionSubject'],'next');
  questionService.subscribeToReturnedObservable(observable,questionService['editQuestionSubject']);
  observable.subscribe();
  expect(questionService['editQuestionSubject'].next).toHaveBeenCalled();
});
});

Но он получает ошибку Expected spy next to have been called.

1 Ответ

0 голосов
/ 21 апреля 2020

Я сделал это (надеясь, что это правильный путь). Целью тестирования является проверка правильности вызова Subject 'next. Поэтому создайте Observable, используя of, и позвольте потоку кода оттуда.

fit('should call send next value for the subject is the response from the server is ok', () => {
  const questionService:QuestionManagementService = TestBed.get(QuestionManagementService);
  const helperService:HelperService = TestBed.get(HelperService);
  const body = {"result":"success", "additional-info":"some additional info"};
  const receivedHttpEvent = new HttpResponse({body:body});
  const expectedResult = new Result('success', 'some additional info');
  spyOn(helperService,'validateServerResponseStructure').and.returnValue(true);
  let observable = of(receivedHttpEvent);
  spyOn(questionService['editQuestionSubject'],'next');
  questionService.subscribeToReturnedObservable(observable,questionService['editQuestionSubject']);
  expect(questionService['editQuestionSubject'].next).toHaveBeenCalledWith(expectedResult);
});
...