來看一個例子,怎么使用 Istanbul 。下面是腳本文件 simple.js 。
~~~
var a = 1;
var b = 1;
if ((a + b) > 2) {
console.log('more than two');
}
~~~
使用?istanbul cover?命令,就能得到覆蓋率。
~~~
$ 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 是可以在瀏覽器打開的覆蓋率報告,其中有詳細信息,到底哪些代碼沒有覆蓋到。
