'How to mock a service in Angular unit testing?

I hve the following service subscription which is promise

getTaskData = async() {
line 1   let response = this.getTaskSV.getTaskData().toPromise();
line 2   this.loading = false;
}

I tried like below,

   it('should load getTaskData', async () => {
     let getTaskSV= TestBed.inject(getTaskSV);
     spyOn(getTaskSV, 'getTaskData').and.returnValue(of([{name: 'test1'}, {name: 'test2'}]));
     component.getTaskData();
     fixture.detectChanges()
  });

When I run the above test case I see the line 1 and 2 are not covered. I am actually new to the test cases. Can any one please help me how to mock this service. Thanks in advance.



Solution 1:[1]

Since it is a service (an external dependency) and you're mocking it by returning a value every time it is called, of course it won't be covered and this is fine.

To cover those lines, write a separate unit test for getTaskSV service.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AliF50