標籤:return console require mkdir main npm exp nod 替代
這篇主要學習:
- 測試架構mocha;
- 斷言庫:should;
- 測試率覆蓋工具 istanbul;
建立並進入lesson3:
mkdir lesson3 && lesson3
建立main.js並編寫測試函數:
var fibonacci = function(n) { if(typeof n !== ‘number‘){ throw new Error(‘n should be a Number‘) } if(n < 0){ throw new Error(‘n should >= 0‘) } if(n > 10){ throw new Error(‘n should <= 10‘) } if(n === 0){ return 0 } if(n === 1){ return 1 } return fibonacci(n-1) + fibonacci(n-2)}if(require.main === module){ var n = Number(process.argv[2]) console.log(‘fibonacci(‘+ n +‘) is‘,fibonacci(n))}exports.fibonacci = fibonacci
lesson3下建立test檔案夾,並建立main.test.js:
mkdir test && cd test && echo.>main.test.js
在main.test.js編寫測試案例:
var main = require(‘../main‘)var should = require(‘should‘)describe(‘test/main.test.js‘,function(){ it(‘should equal 0 when n === 0‘, function(){ main.fibonacci(0).should.equal(0) }) it(‘should equal 1 when n === 1‘, function(){ main.fibonacci(1).should.equal(1) }) it(‘should equal 55 when n === 10‘, function(){ main.fibonacci(10).should.equal(55) }) it(‘should throw when n > 10‘, function (){ (function (){ main.fibonacci(11) }).should.throw(‘n should <= 10‘) }) it(‘should throw when n < 0‘, function(){ (function(){ main.fibonacci(-1) }).should.throw(‘n should >= 0‘) }) it(‘should throw when n isnt Number‘, function(){ (function(){ main.fibonacci(‘逗比‘) }).should.throw(‘n should be a Number‘) })})
cmd輸出:
mocha
如所示則完成測試:
安裝一個 istanbul:
cnpm i istanbul -g
執行:
istanbul cover _mocha
(註:如果window下報找不到_mocha檔案的錯,就找到你電腦中mocha安裝目錄下的_mocha檔案的位置替代_mocha,例:istanbul cover C:\Users\[使用者名稱]\AppData\Roaming\npm\node_modules\mocha\bin\_mocha)
可以看到,其中的分支覆蓋率是 91.67%,行覆蓋率是 87.5%。
前端之 —— node.js摸爬打滾之路(二)