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?
// 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({});
});
}));
});
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étododeletePost
está siendo espiado y la solicitud HTTP real no se está realizando. Por lo tanto, el métodosubscribe
no se está ejecutando.Para probar el método
subscribe
, puedes crear unHttpClient
simulado y proporcionarlo aTestBed
. Luego, utilizaHttpClientTestingModule
en lugar deHttpClientModule
en la matriz de importaciones deTestBed
. Esto interceptará las solicitudes HTTP y te permitirá probar el métodosubscribe
.Aquí tienes un ejemplo de cómo modificar la prueba para lograr esto:
En esta prueba modificada, se inyecta
HttpTestingController
y se utiliza para probar las solicitudes HTTP y sus respuestas. El métodoexpectOne
prueba la URL de la solicitud HTTP y el métodoflush
prueba la respuesta de la solicitud HTTP.