Automated testing with mocha
自動化測試是工程師基本要求。
Why we need tests?
當撰寫一個函式,我們會預期產出的結果,我們可能會帶入不同參數用 console 來檢視結果,但若有錯誤修改後,又要一一測試之前帶入的參數,所以測試跟開發是分開的,測試可以很容易執行,檢查主要使用沒問題。
Behavior Driven Development (BDD)
行為驅動的開發被用在許多專案中,BDD 包含 3 件事測試、文件、範例。
Development of “pow”: the spec
我們要寫一個函式,pow(x, n) 該函式將產出 x 的 n 次方,在創建函式之前可以描述該函式的功能有 3 個規範。
describe("title", function() { ... })描述函式名稱。it("title", function() { ... })描述函式功能assert.equal(value1, value2)帶入參數測試函數的產出是否正確
The development flow
撰寫規範
撰寫基本函式可以跑測試
執行測試框架 mocha ,檢測函示是否正確
增加更多案例到測試中
測試失敗修改函式
重複 3 ~ 5 步驟
The spec in action
測試主要用到 3 個 librarues。
mocha 主要執行的框架 包含
descibeit等函數。chai 有很多 assertions 函式,範例使用
assert.equal。Sinon 用來監視函數模擬內建函式。
頁面分為 5 個部分
head 引入 libraries
script 撰寫測試的函示
測試程式碼寫在 test.js
<div id='mocha'>用來輸出 mocha 執行的結果mocha.run()執行 mocha
Improving the spec
增加更多情況到測試中,一個測試只檢查一個功能。
Improving the implementation
Nested describe
makeTest() 只用在 for 迴圈內,因此將他們綁在一起,下一個測試不會在用到。
Extending the spec
增加規範,程式碼出現錯誤,修改程式碼。
assert.equal(value1, value2)– checks the equalityvalue1 == value2.assert.strictEqual(value1, value2)– checks the strict equalityvalue1 === value2.assert.notEqual,assert.notStrictEqual– inverse checks to the ones above.assert.isTrue(value)– checks thatvalue === trueassert.isFalse(value)– checks thatvalue === false…the full list is in the docs
Last updated
Was this helpful?