Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1.1K
Vistas
Cómo hacer una prueba unitaria de un interceptor HTTP en Angular usando Jasmine

Tengo el interceptor http a continuación en mi aplicación angular y me gustaría realizar una prueba unitaria del mismo usando Jasmine. Busqué en Google algunos de ellos y lo intenté, pero no funciona como se esperaba. Encuentre el siguiente código de archivo HttpInterceptorService.ts

 export class HttpInterceptorService Implements HttpInterceptor { counter = 0; constructor(private loaderService: LoaderService) { } intercept(req: HttpRequest<any>, next: HttpHandler) { if (req.url !== '/getUsers') { this.counter ++; } this.loaderService.setStatus(true); return next.handle(req).pipe( finalize(() => { if (req.url !== 'getUsers') { this.counter --; } if (this.counter === 0) { this.loaderService.setStatus(false); } }; ); } }

A continuación se muestra el código del archivo HttpInterceptor.service.spec.ts que probé a partir de ahora. No estoy seguro de cómo probar el método particular en él.

 describe('HttpInterceptorService', () => { let httpService: HttpService; let httpMock: HttpTestingController; let interceptor: HttpInterceptorService; beforeEach(()=> { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ HttpService, {provide:HTTP_INTERCEPTOR, useClass: HttpInterceptorService, multi: true}, ] }); httpService = TestBed.get(HttpService); httpMock = TestBed.get(HttpTestingController); interceptor = TestBed.get(HttpInterceptorService); }); it('should increment the counter for all api's expect getUsers', ()=> { httpService.get('getAdminList').subscribe(res => { expect(res).toBeTruthy(); expect(interceptor.counter).toBeGreaterThan(0); }); }); });

después de verificar el código de referencia, puedo cubrir algunas líneas de código con los cambios anteriores. Pero todavía no puedo cubrir el método de finalización. Solicitud de amable ayuda.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

el siguiente código ayuda a cubrir el código dentro del operador finalizar.

 const next: any = { handle: () => { return Observable.create(subscriber => { subscriber.complete(); }); } }; const requestMock = new HttpRequest('GET', '/test'); interceptor.intercept(requestMock, next).subscribe(() => { expect(interceptor.counter).toBeGreaterThan(0); });
over 4 years ago · Santiago Trujillo Denunciar

0

Elimine HttpInterceptorService de los proveedores porque ya lo está proporcionando en la siguiente línea con { provide:HTTP_INTERCEPTOR, ... . Intente seguir esta guía: https://alligator.io/angular/testing-http-interceptors/ . Parece que necesita tener un servicio que realmente haga llamadas a la API. Intente seguir esta guía también: https://www.mobiquity.com/insights/testing-angular-http-communication

Creo que para hacer una llamada HTTP, puede simplemente hacer httpClient.get('www.google.com').subscribe() y no debería necesitar un servicio real ( DataService ) como muestra la primera guía.

Editar:

 describe('HttpInterceptorService', () => { let httpService: HttpService; let httpMock: HttpTestingController; let interceptor: HttpInterceptorService; // mock your loaderService to ensure no issues let mockLoaderService = { setStatus: () => void }; beforeEach(()=> { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ HttpService, {provide:HTTP_INTERCEPTOR, useClass: HttpInterceptorService, multi: true}, // provide the mock when the unit test requires // LoaderService { provide: LoaderService, useValue: mockLoaderService }, ] }); httpService = TestBed.get(HttpService); httpMock = TestBed.get(HttpTestingController); interceptor = TestBed.get(HttpInterceptorService); }); it('should increment the counter for all api's except getUsers', ()=> { httpService.get('getAdminList').subscribe(res => { expect(res).toBeTruthy(); expect(interceptor.counter).toBeGreaterThan(0); }); }); // add this unit test it('should decrement the counter for getUsers', ()=> { httpService.get('getUsers').subscribe(res => { expect(res).toBeTruthy(); expect(interceptor.counter).toBe(0); }); }); });
over 4 years ago · Santiago Trujillo Denunciar

0

Ejemplo vivo@

 describe('AuthHttpInterceptor', () => { let http: HttpClient, httpTestingController: HttpTestingController, mockAuthService: AuthorizationService; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule, SharedModule], providers: [ { provide: AuthorizationService, useClass: MockAuthorizationService }, { provide: HTTP_INTERCEPTORS, useClass: AuthorizationInterceptor, multi: true }, // One of these tests trigger a console.error call and is expected // Mocking the logger prevents this otherwise another test run outside this suite // to prevent console.error calls will fail. { provide: LoggerInjectionToken, useValue: mockLogger }] }); http = TestBed.inject(HttpClient); httpTestingController = TestBed.inject(HttpTestingController); mockAuthService = TestBed.inject(AuthorizationService); });

Prueba de ejemplo:

 it('will refresh token and re-issue request should 401 be returned.', (() => { spyOn(mockAuthService, 'requestNewToken').and.callFake(() => { return of({ renewed: true, accessToken: 'token' }); }); http.get('/data') .subscribe((data) => { expect(data).toEqual('Payload'); }); const failedRequest = httpTestingController.match('/data')[0]; failedRequest.error(new ErrorEvent('Er'), { status: 401 }); const successReq = httpTestingController.match('/data')[0]; successReq.flush('Payload', { status: 200, statusText: 'OK' }); expect(mockAuthService.requestNewToken).toHaveBeenCalled(); httpTestingController.verify(); }));

Depende de lo que se necesita directamente

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda