我正在處理現有的 Angular 專案,并且我有以下帶有錯誤處理的攔截器。這是代碼:
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const sendAccessToken = this.moduleConfig.resourceServer.sendAccessToken;
if (sendAccessToken) {
const token = this.authStorage.getItem('access_token');
const header = 'Bearer ' token;
const headers = req.headers.set('Authorization', header);
req = req.clone({ headers });
}
return next.handle(req).pipe(
catchError(err => {
let errorMessage: string;
if (err instanceof HttpErrorResponse) {
switch (err.status) {
case 401: {
errorMessage = 'Autorisation required.';
break;
}
default: {
const erreurText = err.error.messages[0].message
break;
}
}
}
this.toastr.error(errorMessage);
const error = err.error;
return error;
}),
) as any;
}
這是我想觸發catcherror的測驗,但我不知道該怎么做:
it('#should handle incorrect url', () => {
const requestMock = new HttpRequest('GET', '/wrongtest');
interceptor.intercept(requestMock, next).subscribe(() => {
expect(requestMock.headers.has('Authorization')).toEqual(false);
});
});
誰能指導我如何在我的 HttpRequest 中觸發錯誤。
提前致謝。
uj5u.com熱心網友回復:
假設您使用 jasmine 進行測驗:
- 注入所有測驗依賴項:
// Necessary to inject the right HTTP interceptor
const interceptorOf = <T>(type: Type<T>) =>
TestBed
.inject(HTTP_INTERCEPTORS)
.find(interceptor => interceptor instanceof type) as unknown as T
describe('...', () => {
let httpClient: HttpClient
let httpMock: HttpTestingController
let interceptor: ErrorInterceptor
beforeEach(async () =>
await TestBed.configureTestingModule({
imports: [
// Load all your interceptor's dependencies
HttpClientTestingModule,
],
providers: [
{
provide: HTTP_INTERCEPTORS,
deps: [], // Fill with your interceptor's dependencies
useClass: ErrorInterceptor,
multi: true
},
],
}).compileComponents()
httpMock = TestBed.inject(HttpTestingController)
httpClient = TestBed.inject(HttpClient)
interceptor = interceptorOf(ErrorInterceptor)
})
})
- 呼叫普通端點并模擬回應:
it('should do something', async () =>{
const observable$ = httpClient.get(testUrl)
const serviceUnavailable = new HttpErrorResponse({
status: 503,
statusText: 'Service Unavailable',
url: testUrl
})
const httpReqPromise = firstValueFrom(observable$)
httpMock.expectOne(testUrl).flush('error', serviceUnavailable)
try {
await httpReqPromise
fail('It should have not succeeded')
} catch(error) {
expect(error instanceof HttpErrorResponse).toBeTrue()
expect(error.status).toBe(503)
}
})
注1:您的catchError管道使用無效;你不應該回傳一個錯誤,而是一個將被使用而不是崩潰的 observable。
catchError(err => {
...
const error = err.error;
return of(error);
})
注意 2:如果您像我在上面的代碼段中所做的那樣,您的錯誤將被傳播到“下一個”回呼中,該回呼應該將以下承諾決議為成功
it('should do something', async () =>{
const observable$ = httpClient.get(testUrl)
const serviceUnavailable = new HttpErrorResponse({
status: 503,
statusText: 'Service Unavailable',
url: testUrl
})
const httpReqPromise = firstValueFrom(observable$)
httpMock.expectOne(testUrl).flush('error', serviceUnavailable)
try {
const error = await httpReqPromise
expect(error instanceof HttpErrorResponse).toBeTrue()
expect(error.status).toBe(503)
} catch(__) {
fail('It should have not thrown')
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/473824.html
上一篇:測驗NUnit啟動Azure函式
