Mocha介紹
Mocha(發音“摩卡”),是現在最流行的JavaScript測試框架之一,在瀏覽器和Node環境都可以使用;測試框架可以為JavaScript添加測試用例,從而保證代碼質量。
一、語法
測試腳本例子add.js
// 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);
});
});
上面這段代碼,可以獨立執行,可以包含一個或者多個describe塊,每個describe包含一個或者多個it塊
describe
參數 | 說明 |
---|---|
第一個參數 | 測試套件名稱 |
第二個參數 | 實際執行的函數 |
it(是測試最小單位)
參數 | 說明 |
---|---|
第一個參數 | 測試用例的名稱 |
第二個參數 | 實際執行的函數 |
二、斷言庫介紹
expect(add(1, 1)).to.be.equal(2);
所謂的斷言庫就是執行結果是否和預期結果是一致,不一致就會拋出錯誤,上面這句斷言的意思是,調用add(1,1),結果應該等于2
斷言庫有很多種,這里引入的是斷言庫是chai,mocha并不限制使用哪一種斷言庫,下面是一些例子。
// 相等或不相等
expect(4 + 5).to.be.equal(9);
expect(4 + 5).to.be.not.equal(10);
expect(foo).to.be.deep.equal({ bar: 'baz' });
// 布爾值為true
expect('everthing').to.be.ok;
expect(false).to.not.be.ok;
// typeof
expect('test').to.be.a('string');
expect({ foo: 'bar' }).to.be.an('object');
expect(foo).to.be.an.instanceof(Foo);
// include
expect([1,2,3]).to.include(2);
expect('foobar').to.contain('foo');
expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo');
// empty
expect([]).to.be.empty;
expect('').to.be.empty;
expect({}).to.be.empty;
// match
expect('foobar').to.match(/^foo/);
了解更多關于mocha請點擊
三、Karma介紹
Karma是由Google團隊開發的一套前端測試運行框架,它不同于測試框架(比如:mocha),它是運行在這些測試框架之上。主要完成以下工作
- Karma啟動一個web服務器,用于生成包含js測試腳本的頁面
- 運行瀏覽器加載頁面,可以顯示測試的結果
- 如果開啟檢測,當文件有修改時,繼續執行測試用例并且返回測試結果
- 提供代碼覆蓋率
了解更多關于Karma請點擊