前端之 —— node.js摸爬打滾之路(二)

來源:互聯網
上載者:User

標籤: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摸爬打滾之路(二)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.