nodejs代码覆盖率
上一篇 /
下一篇 2018-04-26 14:41:47
/ 个人分类:覆盖率测试
总结最近做nodejs代码覆盖率,主要使用Istanbul包,没有其他语言的覆盖率工具功能多。
1 安装:
[html] view plain copy
$ npm install -g istanbul
nodejs文件test.js内容:
[html] view plain copy
var a = 1;
var b = 1;
if ((a + b) > 2) {
console.log('more than two');
}
运行
[html] view plain copy
$ istanbul cover simple.js
===== Coverage summary =====
Statements : 75% ( 3/4 )
Branches : 50% ( 1/2 )
Functions : 100% ( 0/0 )
Lines : 75% ( 3/4 )
=============================
返回结果显示,simple.js 有4个语句(statement),执行了3个;有2个分支(branch),执行了1个;有0个函数,调用了0个;有 4行代码,执行了3行。
这条命令同时还生成了一个 coverage 子目录,其中的 coverage.json 文件包含覆盖率的原始数据,coverage/lcov-report 是可以 在
浏览器打开的覆盖率报告,其中有详细信息,到底哪些代码没有覆盖到
3 Istanbul参数使用:
[html] view plain copy
$ istanbul check-coverage --statement 90
ERROR: Coverage for statements (75%) does not meet global threshold (90%)
上面命令设置语句覆盖率的门槛是 90% ,结果就报错了,因为实际覆盖率只有75%
[html] view plain copy
$ istanbul cover --handle-sigint simple.js
如果是程序运行时间比较长,比如sever服务,程序不停,添加--handle-sigint参数,发送信号SIGINT,可以生成覆盖率report。
4 忽略某些代码:
[html] view plain copy
var bject = parameter || /* istanbul ignore next */ {};
上面代码是为 object 指定默认值(一个空对象)。如果由于种种原因,没有为 object 为空对象的情况写测试,可以用注释,不将这种情况计入覆盖率。注意,注释要写在"或"运算符的后面。
[html] view plain copy
/* istanbul ignore if */
if (hardToReproduceError)) {
return callback(hardToReproduceError);
上面代码的 if 语句块,在计算覆盖率的时候会被忽略
收藏
举报
TAG: