使用 jasmine 模拟 if/else 语句 - 使用 Angular/Typescript

我在现有函数中添加了一个小修改。我们的质量检查已将其识别为新代码,因此我需要用单元测试覆盖新的 4 行 - 记住,一开始就没有单元测试,而且我添加的函数非常大!


我尝试了多种方法来尝试模拟服务、变量、间谍活动等……但总是出错。我对茉莉花很陌生,所以很挣扎。我需要做的就是进行任何类型的检查以覆盖真值/假值。


组件.ts 文件


hasDescription() {

        return this.isBrilliant() || this.isCool();

    }


isBrilliant() {

        return this.service.Type.description == 'Brilliant';

    }


isCool() {

        return this.service.Type.description == 'Cool';

    }




onExportToExcel(): void {

        var r = [];

        // added the below if/else - any check on this will be suffice.

        if (this.hasDescription()) {

            if (!this.isBrilliant()) {

                r.push('This is Cool');

            } else {

                r.push('This is Brilliant');

            }

            if (!this.isBrilliant()) {

            r.push('More Cool content');

            }

        }

}

我尝试将isBrilliant() 设置为模拟值true,并期望该值是真实的expect(component.isBrilliant()).toBeTruthy();


我尝试通过以下方式在规范文件中设置它:


const isBrilliant = true;

component.isBrilliant = isBrilliant;

然而我在这里得到的错误是Type 'true' is not assignable to type '() => boolean'.


如果任何经验丰富的 jasmine 开发人员可以向我展示一种快速方法来覆盖这个简单的声明,我将不胜感激。谢谢


智慧大石
浏览 106回答 1
1回答

跃然一笑

作为最佳实践的一部分,我建议进行一些更改。不要模拟组件方法,因为您需要测试它们。在您的情况下,您应该设置 value this.service.Type.description,因此它应该返回trueor false。这将是一个正确的做法。如果this.service是已注入的服务construtor,则可以模拟该服务。由于您正在使用 测试多个条件if else,因此您需要编写几个it块才能获得良好的测试覆盖率。要进行测试var r,您应该将其声明public为组件级别的变量,而不是在function. let也更喜欢var.这是一个示例代码,您可以编写该代码来设置其中的值isBrilliant()it('should push Brilliant when the Description is so,()=>{   component.service.Type.description = 'Brilliant';   component.onExportToExcel();   expect(component.r.length).toBe(1);   expect(component.r[0]).toBe('This is Brilliant');})it('should push other cool content when the Description is not Brilliant,()=>{   component.service.Type.description = 'something else';   component.onExportToExcel();   expect(component.r.length).toBe(2);   // check other values in expect block accordingly})// you should also check that "component.r" has zero length when hasDescription() returns false我希望上面的代码片段能给你一个好的开始
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript