Need help to write unit test for the the below scenario:
HttpInterceptor code
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, Observable, throwError } from 'rxjs';
import { UnauthorizedErrorDialogComponent } from 'src/app/shared/components/unauthorized-error-dialog/unauthorized-error-dialog.component';
import { SvDialogService } from 'sv-shared-library';
@Injectable({
providedIn: 'root'
})
export class GlobalErrorIntercepterService
implements HttpInterceptor
{
constructor(private dialog: SvDialogService) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((err) => {
console.log(err);
if (err.status === 401) {
this.dialog.open(UnauthorizedErrorDialogComponent);
}
return throwError(() => new Error(err));
})
);
}
}
Test Cases:-
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, SharedModule],
providers: [
{ provide: SvDialogService, useValue: dialogContext },
{
provide: HTTP_INTERCEPTORS,
useClass: GlobalErrorIntercepterService,
multi: true
},
{
provide: SvDialogService,
useValue: autoSpy(SvDialogService)
}
]
}).compileComponents();
dialogContext = TestBed.inject(SvDialogService);
http = TestBed.inject(HttpClient);
httpMock = TestBed.inject(HttpTestingController);
service = TestBed.inject(GlobalErrorIntercepterService);});
it('Http Error 401', () => {
const url = 'https://www.google.com/';
const mockHandler = {
handle: jest.fn(() =>
throwError(
new HttpErrorResponse({
status: 401,
error: { message: 'Unauthorized' }
})
)
)
};
const req = new HttpRequest('GET', url, {
reportProgress: true
});
service.intercept(req, mockHandler).subscribe({
next: (response) => {
fail('Expected error');
},
error: (err) => {
expect(err).toBeTruthy();
expect(dialogContext.open).toBeCalled();
},
complete: () => {}
}); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.