【问题标题】:angular 8 unit test with jest for http post catchError带有笑话的角度8单元测试,用于http post catchError
【发布时间】:2021-01-04 13:24:25
【问题描述】:

您好,我想要 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 来实现?

【问题讨论】:

    标签: angular unit-testing http ts-jest


    【解决方案1】:

    目前尚不清楚,但您似乎需要等到订阅者触发。您可以为此使用 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();
        }
      });
    });
    

    【讨论】:

    • 我只是尝试用红色覆盖代码,并且已经尝试过 expect(err).toEqual({error: 400})。
    猜你喜欢
    • 2022-01-07
    • 2021-09-23
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2018-06-17
    相关资源
    最近更新 更多