在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 (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...