我有一个函数,单元测试的覆盖率是75%,但是,我希望单元测试的覆盖率是100%。这是函数:
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;
}
}下面是我为这个方法编写的所有单元测试:
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);
});
});但是,如果在运行npm run test-cover && npm run cover-report时进行测试,则无法获得第一个嵌套
我得到了100%的通过测试,但75%的分支被覆盖,因为它说测试不包括:

这种情况:
if (this.averageRating % 1 > 0) {
this.noRatings--;
}没有被测试覆盖,我想知道为什么?不管我怎么试,我都不能把它检测出来。你能帮帮我吗?
发布于 2021-10-25 06:43:04
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();
});https://stackoverflow.com/questions/69703212
复制相似问题