M Y*_*Yil 4 unit-testing angular-http-interceptors angular
我一直在寻找测试 Angular Interceptor 代码的错误处理方法,但我似乎不知道如何进行。
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService, private router: Router) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(err => {
let errorMessage = '';
if (err instanceof HttpErrorResponse) { // server side error
switch (err.status) {
case 401:
// auto logout if 401 response returned from api
errorMessage = "Ongeldige inloggegevens"
break;
case 500: //server error
errorMessage = `Error Status: ${err.status}\nMessage: ${err.message}`;
this.router.navigate([`/code500`]);
break;
}
return throwError(errorMessage);
}
})
)
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
尝试这样的事情,希望有帮助。
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorInterceptor } from './ErrorInterceptor';
import { of } from 'rxjs';
import { take } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http';
import { AuthenticationService } from '....';
describe('ErrorInterceptor', () => {
let interceptor: ErrorInterceptor;
let mockAuthenticationService: AuthenticationService;
beforeEach(() => {
mockAuthenticationService = {
logout: jasmine.createSpy('logout')
};
mockRouter = {
navigate: jasmine.createSpy('navigate')
};
interceptor = new ErrorInterceptor(mockAuthenticationService as any, mockRouter as any);
});
describe('intercept', () => {
beforeEach(() => {
const payload = {
status: 401
},
response = new HttpErrorResponse(payload),
next: any = {
handle: jasmine.createSpy('handle').and.callFake(() => of(response))
};
interceptor.intercept(response as any, next).pipe(take(1))
.subscribe();
});
describe('when status is 401', () => {
it('should logout', () => {
expect(mockAuthenticationService.logout).toHaveBeenCalled();
expect(mockRouter.navigate).toHaveBeenCalledWith([`\logout`]);
});
});
...
});
Run Code Online (Sandbox Code Playgroud)