我有以下代码,我在其中查找出错的自定义标头:
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();
});不确定问题在哪里,但status和statusText按预期通过,但不包括标头,因此if块未激活。
有什么建议吗?
发布于 2020-12-16 15:54:56
应该能行得通。下面是一个使用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' },
});
});
});单元测试结果:

https://stackoverflow.com/questions/60381453
复制相似问题