mocha的使用總結

一.mocha的安裝和運行

1.安裝:

# 1.能夠全局安裝
npm install -g mocha

# 2.也能夠在項目中安裝
npm install -D mocha
複製代碼

2.測試啓動命令

  • 使用以下的命令時,mocha會默認執行當前路徑的test/目錄下的全部測試文件
# 1.若mocha是全局安裝的
mocha

# 2.若mocha是在項目中安裝的
node_module\mocha\bin\mocha
複製代碼

3.項目目錄結構:

在項目下新建一個test/目錄,爲默認的測試文件存放位置javascript

my_project/
—— hello.js                 // 含有待測試內容的文件
—— test/                    // test/目錄存放全部的測試文件
———— hello_test.js              // 測試文件
———— ...                        // ...
—— package.json             // 項目描述文件
—— node_modules/            // npm安裝包
複製代碼

二.mocha測試文件的基本寫法:

一個測試文件的內容主要寫法有三部分:java

  1. describe(groupName, callback)測試分組describe能夠多層嵌套使用
  2. it('testItemName', callback)測試項
    • 注意:
      • 測試同步函數時,callback內無需傳入參數
      • 測試異步函數時,callback內須要傳入一個參數,一般命名爲done
  3. 斷言:對測試內容的判斷,斷言是否知足
    • 默認使用的是Node.js的assert模塊
    • 也能夠本身選擇其餘的斷言庫:
      • 斷言庫列表:
        • should.jsshould語法風格BDD風格)的斷言庫
        • expect.jsexpect語法風格簡約BDD風格)的斷言庫
        • chai:可自由在(assert()should()expect())三種風格進行選擇的斷言庫
        • better-assert:~
        • unexpected: ~
      • 第三方斷言庫的使用方法:
        1. 方式1:在每一個測試文件中都使用require引入斷言庫依賴,而後便可在當前的測試文件中使用了
        2. 方式2:在test/目錄下添加一個mocha.opts配置文件,在裏面寫入要使用的斷言庫,以後便可在全部的測試文件中直接使用了,例如:
        // test/mocha.opts
        --require should
        複製代碼

示例:

// hello.js
module.exports = function (...rest) {
    var sum = 0;
    for (let n of rest) {
        sum += n;
    }
    return sum;
};
複製代碼
// test/hello.test.js
const assert = require('assert');
const sum = require('../hello');

describe('#hello.js', () => {
    describe('#sum()', () => {
        it('sum() should return 0', () => {
            assert.strictEqual(sum(), 0);
        });
        it('sum(1) should return 1', () => {
            assert.strictEqual(sum(1), 1);
        });
        it('sum(1, 2) should return 3', () => {
            assert.strictEqual(sum(1, 2), 3);
        });
        it('sum(1, 2, 3) should return 6', () => {
            assert.strictEqual(sum(1, 2, 3), 6);
        });
    })
})
複製代碼

命令行輸入mocha開啓測試,控制檯輸出以下的結果,說明編寫的4個測試項所有經過了node

#hello.js
    #sum()
      ✓ sum() should return 0
      ✓ sum(1) should return 1
      ✓ sum(1, 2) should return 3
      ✓ sum(1, 2, 3) should return 6
  4 passing (7ms)
複製代碼

三.mocha的高級用法:

1. mocha爲每一個測試組(describe)提供了以下幾個鉤子函數:

  1. before(fn)fn會在該組中的全部測試項被測試以前調用
  2. after(fn)fn會在該組中的全部測試項被測試以後調用
  3. beforeEach(fn)fn會在該組中每個測試項被調用以前調用
  4. afterEach(fn)fn會在該組中每個測試項被調用以前調用
describe('hooks', function() {
  before(function() {
    // runs before all tests in this block
  });
  after(function() {
    // runs after all tests in this block
  });
  beforeEach(function() {
    // runs before each test in this block
  });
  afterEach(function() {
    // runs after each test in this block
  });

  // test cases
  it('測試項1', () => {
      ...
  })
  it('測試項2', () => {
      ...
  })
});
複製代碼

2.異步測試:

  1. 有以下一個異步函數須要進行測試:
// async.js
const fs = require('fs');

module.exports = async () => {
    let expression =await fs.readFile('./data.txt', 'utf-8');
    let fn = new Function('return ' + expression);
    let r = fn();
    console.log(`Calculate: ${expression} = ${r}`);
    return r;
}
複製代碼
// data.txt
1 + (2 + 4) * (9 - 2) / 3
複製代碼
  1. 對於異步函數的測試,it(測試項名, callback(done) {...})callback中須要傳入一個done參數
    • 若異步測試經過,則在callback內部手動調用done()
    • 若異步測試不經過,則在callback內部手動調用done(err)

    ps:針對不一樣寫法的異步函數,其對應的測試寫法也有所不一樣:express

// async-test.js
const assert = require('assert');
const hello = require('../hello.js');

describe('#async hello', () => {
  describe('#asyncCalculate()', () => {
    
    // 1.若是待測試的異步函數是回調函數語法的,則必須在回調函數中來進行測試判斷(寫法麻煩) 
    it('test async function', function(done) {
        fs.readFile('filepath', function (err, data) {
            if (err) {
                done(err);
            } else {
                done();
            }
        });  
    })
    
    // 2.若是待測試的異步函數是async/await 語法的,可經過try catch來測試判斷(寫法仍是比較麻煩)
    it('#test async function', (done) => {
        (async function () {
            try {
                let r = await hello();
                assert.strictEqual(r, 15);
                done();
            } catch (err) {
                done(err);
            }
        })();
    });

    // 3.待測試的異步函數是async/await語法的,最簡單的寫法——把async函數看成同步函數來測試!!!
    it('test async function', async () => {
        let r = await hello();
        assert.strictEqual(r, 15);
    })
  })  
})
複製代碼
  • 總結: 對於異步函數的測試,若異步函數是使用的async\await關鍵字,其在編寫測試用例時很簡單,基本跟同步函數的測試用例寫法同樣
相關文章
相關標籤/搜索