首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Angular中使用Karma-Jasmine对嵌套的if条件进行单元测试?

如何在Angular中使用Karma-Jasmine对嵌套的if条件进行单元测试?
EN

Stack Overflow用户
提问于 2021-10-25 05:25:51
回答 1查看 351关注 0票数 0

我有一个函数,单元测试的覆盖率是75%,但是,我希望单元测试的覆盖率是100%。这是函数:

代码语言:javascript
复制
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;
    }
}

下面是我为这个方法编写的所有单元测试:

代码语言:javascript
复制
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%的分支被覆盖,因为它说测试不包括:

这种情况:

代码语言:javascript
复制
if (this.averageRating % 1 > 0) {
    this.noRatings--;
}

没有被测试覆盖,我想知道为什么?不管我怎么试,我都不能把它检测出来。你能帮帮我吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-25 06:43:04

代码语言:javascript
复制
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();
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69703212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档