簡體   English   中英

angular 8 單元測試與 http 后 catchError 的玩笑

[英]angular 8 unit test with jest for http post catchError

您好,我想要 http 帖子的單元測試覆蓋 catchError 分支:

 getSession() {
    const options = {
      headers: {
        'Content-Type': 'application/json',
        'Accept-API-Version': 'resource=2.0'
      }
    };
    return this.http.post(SESSION_REST_API_URL, '', options as any)
      .pipe(
        timeoutWith(10000, throwError(new Error('exceeded'))),
        catchError((error: any) => throwError(error))
      );
  }

在我的測試“它”中,我嘗試在訂閱此帖子時收聽toHaveReturnedWithtoEqual但未涵蓋:

it('should throwError', () => {
  // arrange
  const error = throwError({error: 400});
  const options = {headers: {'Content-Type': 'application/json',, 'Accept-API-Version': 'resource=2.0'}}
  ;
  UtilsTest.mockReturnValue(service['http'], 'post', throwError(error));
  // act
  service.getSession();
  // assert 1
  expect(service['http'].post(SESSION_REST_API_URL, '', options)).toHaveReturnedWith(of({error: 400}));
  // assert 2
  expect(loginCredentialsService.getSessionJsonResponse()).toHaveReturnedWith(error)
  // assert 3
  service['http'].post(SESSION_REST_API_URL, '', options).subscribe({
    error: (err) => {
      expect(err).toEqual({error: 400});
    }
  });
});

一些 id 來實現這一目標? 在此處輸入圖像描述

目前尚不清楚,但似乎您需要等到訂閱者開火。 您可以為此使用 Marble 測試 ( https://rxjs-dev.firebaseapp.com/guide/testing/marble-testing )。 或者如果它很簡單,你可以使用如下所示

您好,我想要 http 帖子的單元測試覆蓋 catchError 分支:

it('should throwError', (done) => {
  .....
  service['http'].post(SESSION_REST_API_URL, '', options).subscribe({
    error: (err) => {
      expect(err).toEqual({error: 400});
      done();
    }
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM