首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带自定义头的Angular - Unit-test HttpErrorResponse (HttpClientTestingModule)

带自定义头的Angular - Unit-test HttpErrorResponse (HttpClientTestingModule)
EN

Stack Overflow用户
提问于 2020-02-25 01:53:41
回答 1查看 383关注 0票数 1

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

代码语言:javascript
复制
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并尝试按如下方式进行测试:

代码语言:javascript
复制
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块未激活。

有什么建议吗?

EN

回答 1

Stack Overflow用户

发布于 2020-12-16 15:54:56

应该能行得通。下面是一个使用angular v11+的工作示例

例如。

auth.service.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
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' },
    });
  });
});

单元测试结果:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60381453

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档