Home > Software design >  How to unit test a nested if condition in with Karma-Jasmine in Angular?
How to unit test a nested if condition in with Karma-Jasmine in Angular?

Time:10-26

I have a function and I have a coverage of 75% with unit tests, however, I'd like to have a 100% of coverage of unit tests. This is the function:

calculateRatingSummary(): void {
    if (this.averageRating > 0) {
        this.avgRatings = Math.trunc(this.averageRating);
        this.avgRatingCollection.length = this.avgRatings;
        this.noRatings = this.totalRating - this.avgRatings;
        if (this.averageRating % 1 > 0) {
            this.noRatings--;
        }
        this.noRatingsCollection.length = this.noRatings;
     } else {
        this.noRatingsCollection.length = this.totalRating;
    }
}

And this are all the unit tests I've written for this method:

describe('calculateRatingSummary', () => {
        it('check if company has peer review average rating', () => {
            component.averageRating = 2.3;
            component.calculateRatingSummary();
            expect(component.avgRatingCollection).not.toBeFalse();
        });
        it('rating display with no decimals if it has or not', () => {
            component.averageRating = 3.6;
            component.calculateRatingSummary();
            expect(component.avgRatings).toEqual(3);
        });
        it('all rating stars displays as light shaded when averageRating is smaller than zero', () => {
            component.averageRating = 0;
            component.calculateRatingSummary();
            expect(component.noRatingsCollection.length).toEqual(5);
        });
        it('if averageRating has decimals, noRatings is noRatings minus 1', () => {
            component.averageRating = 4.1;
            component.calculateRatingSummary();
            expect(component.noRatings).toEqual(component.noRatings);
        });
    });

But I can't get the first nested if tested when I run an npm run test-cover && npm run cover-report

I get a 100% of passed tests but 75% of branches covered because it says is not covered by tests:

Coverage report

This condition:

if (this.averageRating % 1 > 0) {
    this.noRatings--;
}

is not being covered by tests and I wonder why? I can't get it tested no matter what I try. Can you help me?

CodePudding user response:

I think else condition is not met in any specs you are expecting, you can try this it might work as our motive is to satisy the else condition i.e.. this.averageRating % 1 < 0

Example spec -
it('if averageRating modulos 1 equal to less than 0', () => {
        component.averageRating = 2;
        component.calculateRatingSummary();
        expect(component).toBeTruthy();
});
  • Related