首页 > 解决方案 > 我如何对这个处理可观察对象的函数进行单元测试

问题描述

我创建了这个函数,因为对于我的应用程序使用 发出的所有请求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.

标签: rxjsangular6angular-test

解决方案


我这样做了(希望这是正确的方法)。测试的范围是检查Subject's next是否被正确调用。所以创建一个Observableusingof并让代码从那里流动。

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);
});

推荐阅读