我在现有功能中添加了一个小修改。我们的质量检查已将其识别为新代码,因此我需要使用单元测试覆盖新的4行-记住从来没有开始过单元测试,而且我添加的功能非常大!
我尝试了多种方法来尝试模拟服务,变量,间谍等等……但总是会出错。我是茉莉的新手,所以苦苦挣扎。我需要做的就是获取各种检查以掩盖真假行。
component.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'.
如果有经验的茉莉花开发者可以向我展示一种快速的方法来获得有关此简单声明的一些知识,将不胜感激。谢谢
更新:
我可以isBrilliant()
成为对或错。我现在需要检查数组r以查看是否已.push
输入正确的字符串?有任何想法吗?
作为最佳实践的一部分,我建议进行一些更改。
this.service.Type.description
并因此应返回true
或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
我希望以上代码片段能给您一个良好的开端
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句