Я использую Angular 8.
Я пытаюсь выполнить модульный тест на HttpInterceptor и перенаправить на страницу с ошибкой при получении фатальной ошибки.
Как мне продолжить работу с моимконтрольная работа? Я просто делаю тест на метод errorHandler сам? Или мне нужно запустить его с точки зрения запроса?
error-handler.interceptor.ts:
export class ErrorHandlerInterceptor implements HttpInterceptor {
log: Logger;
constructor(private noti: NotificationCenterService, private router: Router, private http: HttpClient) {
this.log = new Logger(http, 'ErrorHandlerInterceptor');
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(error => this.errorHandler(error)));
}
// Customize the default error handler here if needed
private errorHandler(error: HttpErrorResponse): Observable<HttpEvent<any>> {
const errorMsg = error.error.message || error.error || error.statusText;
if (error.status === undefined || error.status === null || error.status === 500 || error.status === 0) {
//redirect to error page
this.router.navigate(['fatalerror']);
} else {
//show in notification
this.noti.open(errorMsg, 'OK');
}
this.log.info("ErrorHandlerInterceptor - Error not caught!");
throw error;
}
}
app-routing. модули:
...
const routes: Routes = [
Shell.childRoutes([{ path: 'fatalerror', loadChildren: './shared/fatalerror/fatalerror.module#FatalerrorModule' }]),
{ path: '**', redirectTo: '', pathMatch: 'full' }
];
...
обработка ошибок. interceptor.spec.ts:
import { Type } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HTTP_INTERCEPTORS, HttpClient } from '@angular/common/http';
import { RouterTestingModule } from '@angular/router/testing';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
import { ErrorHandlerInterceptor } from './error-handler.interceptor';
import { NotificationCenterService } from '@app/shared/notification-center.service';
describe('ErrorHandlerInterceptor', () => {
let errorHandlerInterceptor: ErrorHandlerInterceptor;
let http: HttpClient;
let httpMock: HttpTestingController;
let noti: jasmine.SpyObj<NotificationCenterService>;
let router: Router;
function createInterceptor() {
errorHandlerInterceptor = new ErrorHandlerInterceptor(noti, router, http);
return errorHandlerInterceptor;
}
beforeEach(() => {
const spy = jasmine.createSpyObj('NotificationCenterService', ['open']);
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, RouterTestingModule.withRoutes(routes)],
providers: [
{
provide: HTTP_INTERCEPTORS,
useFactory: createInterceptor,
multi: true
},
{
provide: NotificationCenterService,
useValue: spy
}
]
});
noti = TestBed.get(NotificationCenterService);
http = TestBed.get(HttpClient);
httpMock = TestBed.get(HttpTestingController as Type<HttpTestingController>);
router = TestBed.get(Router);
});
afterEach(() => {
httpMock.verify();
});
it('should redirect to fatal error page upon fatal error', () => {
spyOn(ErrorHandlerInterceptor.prototype as any, 'errorHandler').and.callThrough();
//how to proceed
});
});