Skip to content

Instantly share code, notes, and snippets.

@jaceju
Last active October 19, 2016 06:18
Show Gist options
  • Save jaceju/7b6f2265a5225c2c94ba9a4954775b01 to your computer and use it in GitHub Desktop.
Save jaceju/7b6f2265a5225c2c94ba9a4954775b01 to your computer and use it in GitHub Desktop.
Mocha 測試寫法指引

Mocha 測試寫法 Patterns

require 一律放在最前面

儘可能不要在 describeit 中使用 require

把待測試的類別引用放在工具引用的後面

例如:

const chai = require('chai');
const MyClass = require('../src/my-class');

describe 一律使用名詞

describe('The Auth module', () => {
   // …
});

it 一律用來描述行為

it 是待測目標的代稱,故 it 後面要接行為的描述。

it('should get user data after user logged-in', () =>
   // ...
});

it 一律回傳 promise

因為 mocha 支援 promise ,所以應該使用 promise 回傳。

儘量不使用 done

以回傳 promise 為優先,除非情境很難用 promise ,才考慮使用 done 。

Assertion 一律以 should 為優先

以語意優先,所以 assertion 一律使用 should ,除非有 should 無法使用的場合,才用 expect 。

不要在 spy 裡面呼叫 done()

這樣 spy 做完事後,就無法被 sinon.assert 驗證了。

before / beforeEach / after / afterEach 也要回傳 promise

確保每個測試案例執行前後該做的事都有做完,除非無法使用 promise 才考慮呼叫 done()

@Rukeith
Copy link

Rukeith commented Oct 19, 2016

好奇所說的不是用 done
一般不是最後要 done 測試才算結束?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment