Search code examples
angulartestingangular-unit-test

How do I write test cases to cover the lines within subsribe callback function


In my component, I have this code:

setTakenNcatsNames(): void {
    if (this.settings.route){

    this.dataService.getAll(this.settings.route).subscribe(result => 
    {
            console.log('in herer');
            this.arrTakenNcatsNames = result
        });
    }
}

How do I write test cases to cover the lines within the .subscribe() callback? My lines within the .subscribe always show up as not covered no matter what I try.[2]

My coverage always show me this:

`

setTakenNcatsNames(): void {
        Eif (this.settings.route){
            this.dataService.getAll(this.settings.route).subscribe(result => {
                **console.log('in herer');**
                **this.arrTakenNcatsNames = result**
            });
        }
    }

`

Here is my test case for it, what am I missing here?

describe('setTakenNcatsNames()', () => {
    fit('sets the array for taken NCATS names', fakeAsync(() => {
        component.setTakenNcatsNames();
    }));
});

Solution

  • add spy for dataService.getAll

    fit('sets the array for taken NCATS names', fakeAsync(() => {
        const service: DataService = TestBed.get(DataService);
        spyOn(service, "getAll").and.returnValue(of('test');// create a mock result instead of test
        component.setTakenNcatsNames();
        expect(component.arrTakenNcatsNames ).toBe('test');// or mock result 
        }));
    

    This way you can test the block under subscribe