简体   繁体   English

使用 Jest 对 HttpInterceptor 进行单元测试

[英]Unit testing HttpInterceptor using Jest

Need help to write unit test for the the below scenario:需要帮助为以下场景编写单元测试:

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

Test Cases:-测试用例:-

  1. If the error status is 401 the dialog box should open如果错误状态为 401,则应打开对话框
  2. If the error status is not 401 if should throw error如果错误状态不是 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.

相关问题 单元测试Angular 4中的HttpInterceptor - Unit testing HttpInterceptor from Angular 4 单元测试角度HttpInterceptor重试 - Unit Testing angular HttpInterceptor retry 茉莉花单元测试HttpInterceptor验证方法参数 - Jasmine Unit testing HttpInterceptor validating method argument NativeScript - 单元测试 HttpInterceptor NSLocationStrategy 错误 - NativeScript - unit testing an HttpInterceptor NSLocationStrategy error Angular 单元测试 - 在 HttpInterceptor 中测试 retryWhen - Angular unit test - testing retryWhen in HttpInterceptor 使用Jest进行无法理解的单元测试效果错误 - Ununderstandable unit testing effects error using Jest Angular 11:对 HttpInterceptor 进行单元测试 - 异步计时器或 AfterAll 错误 - Angular 11: Unit testing an HttpInterceptor - async timer or AfterAll errors Angular 10:使用修改响应的 HttpInterceptor 进行单元测试,但未获得 HttpResponse - Angular 10: Unit Testing with a HttpInterceptor that modifies the response not getting an HttpResponse 如何在 Angular 中模拟自定义对话框以使用 Jest 进行单元测试 - How to mock Custom Dialog in Angular for Unit Testing using Jest 应该将 Snapshot jest 单元测试与 Angular 匹配 - Should Match Snapshot jest unit testing with Angular
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM