1

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?

enter image description here

//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({});
    });
  }));
});
Lin Du
  • 88,126
  • 95
  • 281
  • 483
carlos
  • 591
  • 1
  • 5
  • 15
  • BTW, it's generally accepted that unless you're writing tests for safety-critical systems, trying to reach the "100% code-coverage" is a waste of misdirected effort: https://stackoverflow.com/questions/3123777/is-100-code-coverage-a-really-good-thing-when-doing-unit-tests - so don't worry too much about small gaps in coverage. – Dai Dec 23 '21 at 00:59
  • Have you used your step-through debugger to set a breakpoint inside the `deletePost`'s `subscribe` callback to see what's going on? – Dai Dec 23 '21 at 01:00

1 Answers1

0

Try below in the providers section

{
provide: PostService,
useClass: mockPostService
}

and you have to create a Class at the top like below:

export class mockPostService{
deletePost(): Observable<any>{
    return of(<Your Mocked data>);
}
}

this should work

desertnaut
  • 57,590
  • 26
  • 140
  • 166