【问题标题】:Angular - Unit-test HttpErrorResponse with custom headers (HttpClientTestingModule)Angular - 带有自定义标头的单元测试 HttpErrorResponse (HttpClientTestingModule)
【发布时间】:2020-02-24 17:53:41
【问题描述】:

我有以下代码,我在其中查找错误的自定义标头:

login(credentials: Credentials): Observable<any> {
    return this.http.post(loginUrl, credentials)
        .pipe(
            catchError((httpErrorResponse: HttpErrorResponse) => {
                let error = new Error('', httpErrorResponse.status);

                ...
                if (httpErrorResponse.headers.get('customHeaderName')) {
                    error.message = 'Appropriate Response';
                }
                ...
                return throwError(error);
            })
        );
}

我正在使用HttpClientTestingModule 并尝试按如下方式进行测试:

it('should catch error with custom header', (done) => {
    authService.login(credentials)
        .subscribe({
            next: null,
            error: (error: Error) => {
                expect(error.message).toEqual('Appropriate Response');
            }
        });

    httpMock.expectOne({
        url: apiUrl,
        method: 'POST'
    }).flush([], {status: 403, statusText: 'Forbidden', headers: {'customHeaderName': 'customHeaderValue'}});

    done();
});

不确定问题出在哪里,但 statusstatusText 按预期通过,但不包含标头,因此未激活 if 块。

有什么建议吗?

【问题讨论】:

    标签: angular typescript unit-testing karma-jasmine angular-httpclient


    【解决方案1】:

    它应该工作。这是一个使用angular v11+的工作示例

    例如

    auth.service.ts:

    import { HttpClient, HttpErrorResponse } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    import { Observable, throwError } from 'rxjs';
    import { catchError } from 'rxjs/operators';
    
    type Credentials = any;
    
    @Injectable()
    export class AuthService {
      constructor(private http: HttpClient) {}
      login(credentials: Credentials): Observable<any> {
        const loginUrl = 'http://localhost:3000/login';
        return this.http.post(loginUrl, credentials).pipe(
          catchError((httpErrorResponse: HttpErrorResponse) => {
            let error = new Error('' + httpErrorResponse.status);
            if (httpErrorResponse.headers.get('customHeaderName')) {
              error.message = 'Appropriate Response';
            }
            return throwError(error);
          })
        );
      }
    }
    

    auth.service.spec.ts:

    import {
      HttpClientTestingModule,
      HttpTestingController,
    } from '@angular/common/http/testing';
    import { TestBed } from '@angular/core/testing';
    import { AuthService } from './auth.service';
    
    fdescribe('60381453', () => {
      let authService: AuthService;
      let httpMock: HttpTestingController;
      beforeEach(() => {
        TestBed.configureTestingModule({
          imports: [HttpClientTestingModule],
          providers: [AuthService],
        });
        authService = TestBed.inject(AuthService);
        httpMock = TestBed.inject(HttpTestingController);
      });
      it('should catch error with custom header', () => {
        const credentials = { password: '123', email: 'teresa.teng@example.com' };
        const apiUrl = 'http://localhost:3000/login';
        authService.login(credentials).subscribe({
          next: null,
          error: (error: Error) => {
            expect(error.message).toEqual('Appropriate Response');
          },
        });
    
        httpMock.expectOne({ url: apiUrl, method: 'POST' }).flush([], {
          status: 403,
          statusText: 'Forbidden',
          headers: { customHeaderName: 'customHeaderValue' },
        });
      });
    });
    

    单元测试结果:

    【讨论】:

      猜你喜欢
      • 2019-03-20
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      • 2021-12-19
      • 1970-01-01
      • 2021-06-24
      相关资源
      最近更新 更多