我有以下代码,其中我查找错误时的自定义标头:
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块未激活。
有什么建议吗?
答案 0 :(得分:0)
应该可以。这是一个使用from datetime import datetime, timezone
import pytz
s = '20200901-01u30m30s'
local_tz = 'Europe/Amsterdam'
# if s represents local time, just localize:
dtobj_tz = pytz.timezone(local_tz).localize(datetime.strptime(s, '%Y%m%d-%Hu%Mm%Ss'))
# datetime.datetime(2020, 9, 1, 1, 30, 30, tzinfo=<DstTzInfo 'Europe/Amsterdam' CEST+2:00:00 DST>)
# if s represents UTC, set it directly:
dtobj_utc = datetime.strptime(s, '%Y%m%d-%Hu%Mm%Ss').replace(tzinfo=timezone.utc)
# ...and convert to desired tz:
dtobj_tz = dtobj_utc.astimezone(pytz.timezone(local_tz))
# datetime.datetime(2020, 9, 1, 3, 30, 30, tzinfo=<DstTzInfo 'Europe/Amsterdam' CEST+2:00:00 DST>)
v11 +
例如
angular
:
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
单元测试结果: