Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.1K
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!