1

この関数を作成したのは、アプリケーションが を使用して送信するすべての要求に対してhttp.post、これがさまざまな部分が応答を処理する方法だからです。そこで、コードを複製するのではなく、関数を作成することを考えました。エラーハンドリングをシミュレートしたいので、 を使おうと思いますmarbel testing。テスト ケースemitsにエラー メッセージが表示されることはわかりますが、テストはまだ失敗します。私は何を間違っていますか

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) => { //THIS IS THE CODE I WANT TO TEST
        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);
  }

これまでに書いたテストは

fit('should call next for the subject if the response from the server is error', () => {
      const questionService:QuestionManagementService = TestBed.get(QuestionManagementService);
      const serverErrorResponse = {
        result: "error",
        ['additional-info']: "reason for error",
        ['http-status']: "304",
        ['http-status-text']: "not found"
      };
      const testScheduler = new TestScheduler((actual,expected)=>{
        expect(actual).toEqual(expected);
      });
      spyOn(questionService['editQuestionSubject'],'next');
      testScheduler.run(helpers=>{
        const { cold, expectObservable, expectSubscriptions } = helpers;
        const expectedMarble = '#|';//error
        const expectedIngridients = {a:serverErrorResponse};
        const observable = cold(expectedMarble,{},serverErrorResponse);

        questionService.subscribeToReturnedObservable(observable,questionService['editQuestionSubject']);
        const expectedResult = new Result(messages.error, 'Error code: 304. not found. error: reason for error');
        expect(questionService['editQuestionSubject'].next).toHaveBeenCalledWith(expectedResult);
      });

しかし、それはエラーになりますExpected spy next to have been called with [ Result({ result: 'error', additionalInfo: 'Error code: 304. not found. error: reason for error' }) ] but it was never called.

エラー値が受信されたことをコード トレースで確認できます。

subscribeToReturnedObservable called
got error from the Observable:  {result: "error", additional-info: "reason for error", http-status: "304", http-status-text: "not found"}
4

1 に答える 1