I'm trying to test a component that calls a http service inside of a method.
But the Karma Coverage is showing "statement not covered" and "function not covered" on the subscribe
method.
What I'm doing wrong? And what's the correct way to test it?
//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({});
});
}));
});