问题描述
我正在尝试为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 (将#修改为@)