pcwu's TIL Notes


[JS] Mocha 新手筆記

Mocha 應該是目前最流行的 JS 測試工具。

Mocha is a feature-rich JavaScript test framework running on Node.js and the browser, making asynchronous testing simple and fun.

相當驚人數量的 npm 套件是使用 mocha 來做測試。

Did you know Mocha is a dependency of over 100,000 projects published to npm alone? Despite this, we’re currently unable to merge most pull requests due to lack of maintenance resources.

Start

這篇教學 测试框架 Mocha 实例教程還滿詳細的,值得一看。

當然官方說明也不能錯過!

Assertion

Mocha 並沒有內建斷言庫,必須從外部引用。斷言庫可以使用 node 內建的 assert

var assert = require('assert');
describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal(-1, [1,2,3].indexOf(4));
    });
  });
});

也可以額外選用,像最熱門的chai

assert 風格:

assert('foo' !== 'bar', 'foo is not bar');
assert(Array.isArray([]), 'empty arrays are arrays');

也有 exceptshould 風格:

expect(4 + 5).to.be.equal(9);
expect([1,2,3]).to.include(2);

foo.should.equal('bar');
foo.should.be.a('string');

Example

假設有一個加法函數:

// add.js
function add(x, y) {
  return x + y;
}

module.exports = add;

可以建立一個「加法函數」的測試:

// add.test.js
var add = require('./add.js');
var expect = require('chai').expect;

describe('加法函數的測試', function() {
  it('1 加 1 應該等於 2', function() {
    expect(add(1, 1)).to.be.equal(2);
  });
});

Mocha 預設會執行 test 資料夾內的測試程式,所以將測試程式放在這邊就可以直接執行 mocha 指令就好。

所以在 package.json 內加上:

"scripts": {
    "test": "mocha"
  }

然後再執行以下指令就可以了:

npm test

Hook

再來就是會常用到的:所有測試執行前/後,每個測試執行前/後

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
});

大概先紀錄這樣!剩下再說!

Reference & Reading