什么是Mocha
Mocha是一個功能豐富的,運行在node.js上的JavaScript的測試框架。
簡單測試
(1)在沒有引入測試框架前的測試代碼
//math.js
module.exports = {
add : (...args) =>{
return args.reduce((prev,curr)=>{
return prev + curr +1;
})
},
mul:(...args) =>{
return args.reduce((prev,curr) =>{
return prev * curr
})
}
}
//test.js
const {add ,mul} = require('./math');
if(add(2,3)===5){
console.log('add(2,3)===5');
}else{
console.log('add(2,3)!==5');
}
(2)引用node assert模塊的測試
上面的測試用例不具有語義化的特點,而通過斷言庫我們可以達到語義化測試用例的目的。
注:assert斷言在測試用例通過時控制台沒有輸出信息,只有錯誤時才會輸出
const assert = require('assert');
const {add ,mul} = require('./math');
assert.equal(add(2,3),6);
除了node的assert的模塊,也有一些第三方斷言庫可以使用,例如Chai。
安裝Mocha
Mocha本身是沒有斷言庫的,如果在測試用例中引入非node自帶的語言庫需要自己安裝。
// 全局安裝 Install with npm globally
npm install --global mocha
// 本地安裝 as a development dependency for your project
npm install --save-dev mocha
使用Mocha
const {should,expect,assert} = require('chai');
const {add,nul} = require('./math');
describe('#math',()=>{
describe('add',()=>{
it('should return 5 when 2 + 3',() =>{
expect(add(2,3),5);
});
it('should return -1 when 2 + -3',() =>{
expect(add(2,-3),-1);
})
})
describe('mul',()=>{
it('should return 6 when 2 * 3',() =>{
expect(add(2,3),6);
});
});
})
運行Mocha,可以通過在package.json中通過配置運行
{
//其它配置...
"scripts": {
"test": "mocha mocha.js"
}
}
然后執行“npm test”命令即可,需要注意的是mocha會檢查統一路徑下的所有文件,所以在在配置時可以指定到特定的某個文件,以免報錯。執行完之后會把結果(無論對錯和執行測試用例的數量還有執行總時長)顯示出來,如下圖所示:
mocha其它功能實例
//只執行其中某條用例
it.only('should return 5 when 2 + 3',() =>{
expect(add(2,3),5);
});
//跳過某條不執行
it.skip('should return 5 when 2 + 3',() =>{
expect(add(2,3),5);
});
測試的覆蓋率
以上我們系的例子代碼量都比較少,僅作為示例,但如果代碼量龐大,我們怎樣保證測試的覆蓋率呢,這就需要一些工具來幫我們檢測,istanbul就是其中一個。
//安裝istanbul
npm install -g istanbul
{
//其它配置...
"scripts": {
"test": "mocha mocha.js",
"cover":"istanbul cover _mocha mocha.js"
}
}
運行stanbul來檢測代碼的覆蓋率,可以通過在package.json中通過來配置。然后通過“npm run cover”這條命令來調用,結果如圖所示:
性能測試
使用了單元覆蓋率會使我們的代碼在正確性上得到一定保證,但在日常測試中,但好有一個問題要考慮,那就是性能。有一些輔助工具可以幫我們達到目的,benchmark就是其一。
npm i --save benchmark
//fn.js
module.exports = {
num1:n =>parseInt(n),
num2:n => Number(n)
}
//benchmark.js
const {num1,num2} = require('./fn');
const Benchmark = require('benchmark');
const suite = new Benchmark.Suite;
suite.add('parseInt',() =>{
num1('123456');
}).add('Number',() =>{
num2('123456')
}).on('cycle',event =>{
console.log(String(event.target))
}).on('complete',function(){
console.log('Faster is '+ this.filter('fastest').map('name'));
}).run({
async:true
});
然后在命令行執行“node benchmark”,稍等幾秒即可看到結果,如圖所示: