[英]How to unit test a nested if condition in with Karma-Jasmine in Angular?
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.我有一个函数,并且单元测试的覆盖率为 75%,但是,我希望单元测试的覆盖率为 100%。 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
但是当我运行
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:我得到 100% 的通过测试,但覆盖了 75% 的分支,因为它说测试没有覆盖:
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?
你能帮助我吗?
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();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.