Increase the coverage summary for function in jasmine

Viewed 326

I have written few functions inside app components. Facing issue in increase the coverage summary on component method.

The test cases are working fine, it just that the few lines are not getting tracked in coverage summary.

app.component.ts

public initializeA(): void {
    this.flagClone.client = {
        build: null, //string
        name: null, //string
        id: null    //string
    }
}

public initializeB(): FlagResult {
    this.isSearch = false;
    return {
        id: null, //string
        description: null,  //string
        url: null,      //string
        client:{
            build: null, //string
            name: null, //string
            id: null    //string
        }
    };
}

app.component.spec.ts respective test cases

const testFlagResult: FlagResult = {
    id: null, //string
    description: null,  //string
    url: null,      //string
    client:{
        build: null, //string
        name: null, //string
        id: null    //string
    }
};
it('should initializeA',() => {
    const mock = spyOn(component,'initializeA').and.returnValue();
    component.initializeA();
    fixture.detectChanges();
    expect(mock).toHaveBeenCalled();
});

it('should initializeB',() => {
    const mock = spyOn(component,'initializeB').and.returnValue(testFlagResult);
    component.initializeB();
    fixture.detectChanges();
    expect(component.isSearch).toBeTruthy();
    expect(mock).toHaveBeenCalled();
});

expecting the below block to be included in coverage summary:

public initializeA(): void {
    this.flagClone.client = {

public initializeB(): FlagResult {
    this.isSearch = false;

Need some inputs that where I am missing it out.

1 Answers

when you add a spy, you are not checking the code being spied on. So by having const mock = spyOn(component,'initializeA').and.returnValue(); you are avoiding testing initializeA and by having const mock = spyOn(component,'initializeB').and.returnValue(testFlagResult); you are not actually testing initializeB

A better implementation would be

it('should initializeA',() => {
    component.initializeA();
    fixture.detectChanges();
    expect(component.flagClone.client).toEqual({
        build: null,
        name: null, 
        id: null    
    });
});

it('should initializeB',() => {
    const expectedResult = {
        id: null, //string
        description: null,  //string
        url: null,      //string
        client:{
            build: null, //string
            name: null, //string
            id: null    //string
        }
    }

    const res = component.initializeB();
    fixture.detectChanges();
    expect(component.isSearch).toBeTruthy();
    expect(res).toEqual(expectedResult);
});

This way you are actually testing that you method is working as desired

Related