如何解决在Angular 8中测试ErrorInterceptor
我正在尝试为ErrorInterceptor编写单元测试:
import { TestBed } from '@angular/core/testing';
import { HttpErrorInterceptorService } from './http-error-interceptor.service';
import { HTTP_INTERCEPTORS,HttpClient,HttpErrorResponse } from '@angular/common/http';
import { HttpClientTestingModule,HttpTestingController } from '@angular/common/http/testing';
import { AuthService } from './auth.service';
const testUrl = '/api/v1/auth/signin';
describe('HttpErrorInterceptorService',() => {
let service: HttpErrorInterceptorService;
let httpMock: HttpTestingController;
let httpClient: HttpClient;
let authService: AuthService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],providers: [
{
provide: HTTP_INTERCEPTORS,useClass: HttpErrorInterceptorService,multi: true,},],});
service = TestBed.inject(HttpErrorInterceptorService);
httpMock = TestBed.inject(HttpTestingController);
httpClient = TestBed.inject(HttpClient);
authService = TestBed.inject(AuthService);
});
it('should be created',() => {
expect(service).toBeTruthy();
});
it('should catch error when calling api',async() => {
const fakeURL = '/api/v1/auth/signin';
const fakeDataToBeSend = {
password: 'Daniel',email: 'daniel.danielecki@foo.com'
};
spyOn(window,'alert');
await authService.login(fakeDataToBeSend).subscribe();
httpMock
.expectOne(fakeURL)
.error(new ErrorEvent('Network error.'));
expect(window.alert).toHaveBeenCalledWith('Network error.');
});
});
在http-error-interceptor.service.ts
中,我有:
import { Injectable } from '@angular/core';
import {
HttpEvent,HttpInterceptor,HttpHandler,HttpRequest,HttpResponse,HttpErrorResponse,} from '@angular/common/http';
import { Observable,throwError } from 'rxjs';
import { retry,catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root',})
export class HttpErrorInterceptorService implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
console.log('--------------')
return next.handle(request).pipe(
retry(1),catchError((error: HttpErrorResponse) => {
console.log('kkkkkkkkkkk')
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
errorMessage = `Error: ${error.error.message}`;
} else {
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
window.alert(errorMessage);
return throwError(errorMessage);
})
);
}
}
在我拥有的身份验证服务中
login(user: ILoginUser): Observable<any> {
return this.http.post<any>('/api/v1/auth/signin',user);
}
我很努力,但是should catch error when calling api
无效。
请帮助
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。