Mocha.js 是什麼?
Mocha 是一款專門在 Node.js 使用的 JavaScript 測試框架,用來撰寫容易閱讀的測試碼,另外再搭配斷言庫( Assertion Library) 驗證測試結果,像是 Chai.js 。
接下來就實際用Mocha撰寫測試看看吧!
專案建立
首先建立一個新的資料夾並建立主程式檔
$ mkdir mocha_demo
$ cd mocha_demo
使用npm init
幫我們建立專案,這個指令會問你一些專案相關的問題,像是名稱、敘述等,如果想之後再填可以使用npm init -y 先建立 package.json 檔,這裡面會記錄專案資訊
$ npm init -y
建立 converter.js 放主要程式。創建一個測試資料夾,裡面放測試的所有檔案
$ touch converter.js
$ mkdir tests
$ touch tests/converter.spec.js
安裝測試框架 mocha 和斷言庫 chai
$ npm i --save-dev mocha chai
撰寫測試程式碼
採用 TDD 開發模式時,會先寫好測試再來撰寫主要程式碼。接下來的範例會以攝氏和華氏溫度的轉換作為這次要撰寫的主程式。
首先打開剛剛建立的 converter.spec.js :
// tests/converter.spec.jsconst { expect } = require('chai')
const { convertToCelcius } = require('../converter')
const { convertToFahrenheit } = require('../converter')describe('Temperature Converter', function () {
describe('Celcius to Fahrenheit conversion', function () {
it('# is not a number', function () {
expect(() => { convertToFahrenheit('a') }).to.throw('The parameter is not a number')
}) it('# converts to Fahrenheit', function () {
expect(convertToFahrenheit(34)).to.equal(93.2)
expect(convertToFahrenheit(0)).to.equal(32)
expect(convertToFahrenheit(100)).to.equal(212)
expect(convertToFahrenheit(-18)).to.equal(-0.4)
})
}) describe('Fahrenheit to Celcius conversion', function () {
it('# is not a number', function () {
expect(() => { convertToFahrenheit('b') }).to.throw('The parameter is not a number')
}) it('# converts to Celcius', function () {
expect(convertToCelcius(32)).to.equal(0)
expect(convertToCelcius(48)).to.equal(8.9)
expect(convertToCelcius(212)).to.equal(100)
expect(convertToCelcius(-10)).to.equal(-23.3)
})
})
})
describe
用來描述測試的情境或形成特定區塊
it
表示一個單獨的測試,做為測試的最小單位,撰寫測試案例的名稱或說明,內部會放程式的預期結果
expect
Chai 斷言庫提供的判斷工具,它提供的語法和口語非常類似,可以一眼看出預期結果是什麼,比方:
expect(convertToCelcius(32)).to.equal(0)
預期結果是 0expect([{a: 1}]).to.deep.include({a: 1})
預期回傳的陣列要包含{a:1}
expect(badFn).to.throw(err);
預期結果會報錯
除了這些語法外,還有很多其他判斷條件,查看這裡有更多用法
撰寫主程式
// converter.jsconst converter = {
convertToFahrenheit: (degree) => {
if (isNaN(degree)) throw new Error('The parameter is not a number')
return Math.round((degree * (9 / 5) + 32) * 10) / 10 //四捨五入
}, convertToCelcius: (degree) => {
if (isNaN(degree)) throw new Error('The parameter is not a number')
return Math.round(((degree - 32) * 5 / 9) * 10) / 10
}
}module.exports = converter
執行測試
在執行測試檔以前,要先在package.json
進行設定,告訴mocha測試檔的位置等。
下面的設定表示在執行npm test
的指令時,mocha 會去 tests
資料夾執行內部所有測試檔案,如果執行 5 秒後都沒回應則會判斷測試不通過,等所有檔案執行完後會自動結束
"scripts": {
"test": "mocha tests --exit --recursive --timeout 5000"
}
接著在終端機執行 npm test
就可以看到測試的結果了
以上就是本次 mocha.js 的簡單示範,如果有任何意見反饋都歡迎留言告訴我!