簡體   English   中英

使用 Jest 對 HttpInterceptor 進行單元測試

[英]Unit testing HttpInterceptor using Jest

需要幫助為以下場景編寫單元測試:

HttpInterceptor代碼

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));
      })
    );
  }
}

測試用例:-

  1. 如果錯誤狀態為 401,則應打開對話框
  2. 如果錯誤狀態不是 401 是否應該拋出錯誤
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: () => {}
}); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM