es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Declaración y funcionalidad no cubiertas al probar un método que llama a un servicio http dentro de un componente.

Estoy tratando de probar un componente que llama a un servicio http dentro de un método. Pero la Cobertura de Karma muestra “sentencia no cubierta” y “función no cubierta” en el método subscribe. ¿Qué estoy haciendo mal? ¿Y cuál es la forma correcta de probarlo?

captura de imagen

// post.service.ts
deletePost(id: number){
    return this.http.delete('https://jsonplaceholder.typicode.com/posts/' + id);
}

// app.component.spec.ts
import { fakeAsync, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { PostService } from './services/post.service';
import { of } from 'rxjs';

describe('AppComponent', () => {
  let postService: PostService;
  let mockPostService: any;
  beforeEach(async () => {
    mockPostService = jasmine.createSpyObj('PostService', ['deletePost'])
    await TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      declarations: [
        AppComponent
      ],
      providers: [
        {
          provide: PostService,
          useValue: mockPostService
        }
      ]
    }).compileComponents();
  });

  it(`should delete a post and the result must be an object {}`, fakeAsync(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;

    mockPostService.deletePost.and.returnValue(of({}));

    spyOn(app, 'deletePost').and.callThrough();
    app.deletePost(1);

    mockPostService.deletePost(1).subscribe((result: any) => {
      expect(result).toEqual({});
    });
  }));
});
Tags:  , , ,

Answer

  1. Avatar for davy.ai

    El problema es que el método subscribe no está siendo cubierto en la cobertura de pruebas. Esto se debe a que el método deletePost está siendo espiado y la solicitud HTTP real no se está realizando. Por lo tanto, el método subscribe no se está ejecutando.

    Para probar el método subscribe, puedes crear un HttpClient simulado y proporcionarlo a TestBed. Luego, utiliza HttpClientTestingModule en lugar de HttpClientModule en la matriz de importaciones de TestBed. Esto interceptará las solicitudes HTTP y te permitirá probar el método subscribe.

    Aquí tienes un ejemplo de cómo modificar la prueba para lograr esto:


    //app.component.spec.ts import { fakeAsync, TestBed } from '@angular/core/testing'; import { AppComponent } from './app.component'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; // añadir HttpTestingController import { PostService } from './services/post.service'; import { of } from 'rxjs'; describe('AppComponent', () => { let postService: PostService; let mockPostService: any; let http: HttpTestingController; // añadir HttpTestingController beforeEach(async () => { mockPostService = jasmine.createSpyObj('PostService', ['deletePost']) await TestBed.configureTestingModule({ imports: [ HttpClientTestingModule // utilizar HttpClientTestingModule en lugar de HttpClientModule ], declarations: [ AppComponent ], providers: [ { provide: postService, useValue: mockPostService } ] }).compileComponents(); http = TestBed.inject(HttpTestingController); // inyectar HttpTestingController }); it(`should delete a post and the result must be an object {}`, fakeAsync(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; mockPostService.deletePost.and.returnValue(of({})); spyOn(app, 'deletePost').and.callThrough(); app.deletePost(1); const req = http.expectOne('https://jsonplaceholder.typicode.com/posts/1'); // comprobar la URL de la solicitud HTTP expect(req.request.method).toEqual('DELETE'); req.flush({}); // comprobar la respuesta de la solicitud HTTP expect(mockPostService.deletePost).toHaveBeenCalledWith(1); expect(app.deletePost).toHaveBeenCalledWith(1); })); });

    En esta prueba modificada, se inyecta HttpTestingController y se utiliza para probar las solicitudes HTTP y sus respuestas. El método expectOne prueba la URL de la solicitud HTTP y el método flush prueba la respuesta de la solicitud HTTP.

Comments are closed.