單元測試 -- mocha + chai

單元測試
單元測試是用來對一個模組、一個函式或者一個類來進行正確性檢驗的測試工作
可以理解為對功能的基本驗證
目前node中的測試框架,一般使用的是 mocha + 斷言庫 chai
安裝
npm install mocha -g npm install mocha npm install chai 複製程式碼
mocha && chai
mocha API
describe
describe 是一個 用例測試集, 他可以進行巢狀
describe('進行首頁的測試', function() { // .... }) 複製程式碼
it
一個it對應一個單元測試用例
it('測試介面xxx', function() { // .... }) 複製程式碼
only skip
only -- 在當前的父describe塊下,只執行該單元的測試
skip -- 在當前的父describe塊下,跳過該單元的測試
describe('Array', function() { describe.only('父describe塊下只執行該測試單元', () => { it.skip('跳過的測試單元', () => { }); }) }) 複製程式碼
describe 和 it 都可以使用這兩個方法
timeout - 設超時
測試集合上定義超時時間,會對這個測試集合中所有的測試用例和測試集合起作用
const sleep = time => new Promise(resolve => setTimeout(resolve, time)) it('timeout', async function () { this.timeout(1000) await sleep(3000) expect(true).to.be.ok }) 複製程式碼

hooks
提供了幾個函式,在特定的事件發生時被觸發
before()、after()、beforeEach()、afterEach()
同一個describe下的執行順序為before、beforeEach、afterEach、after
before, after 執行一次
beforeEach,afterEach 每一個測試用例都會觸發一次
before(() => console.info('首頁測試開始')) after(() => console.info('首頁測試結束')) beforeEach('check check check ', function() { console.log('i am check') }) 複製程式碼
chai API
chai有三種斷言風格,expect,should,assert, 我的專案使用的是 expect
expect
列出幾個常用的方法
方法 | 含義 |
---|---|
equal | 相等(嚴格比較) |
not | 取反 |
include | 包含 |
- 判斷資料型別
expect('username').to.be.a('string') expect(false).to.be.a('boolean') expect(obj).to.have.property('foo') 複製程式碼
非同步測試
專案中的大部分函式為非同步的,這個需要藉助 done 來處理
it(`處理非同步請求`, (done) => { // ... done() }) 複製程式碼
非同步函式在函式內部手動呼叫done()表示測試成功,done(err)表示測試出錯
async await 可以不使用done
it('更新使用者對於文章的態度', async () => { const result = await updateAttitude({ articleId: 123, userId: 131, status: 0}) expect(result).to.be.a('number') }) 複製程式碼
最常見的介面測試
it('獲取某一個頻道下的所有文章列表', async function (){ const result = await chai .request(app) .get('/articles/3/1') .then((res) => { return res.body }) expect(result).to.have.property('data') }) 複製程式碼
測試結果檢查
測試報告
生成測試報告使用的是 mochawesome 模組
"mocha:report": "mocha --reporter mochawesome" 複製程式碼
會自動在專案建立 一個 mochawesome-report 目錄,
