国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

NodeJs測試框架Mocha的安裝與使用

2019-11-19 17:00:19
字體:
來源:轉載
供稿:網友

Mocha是運行在nodejs和瀏覽器下的JavaScript的單元測試框架,官方文檔在https://mochajs.org/,相當的容易上手和好用,單元測試框架其實都差不多,基本都包含下面內容:

用于寫測試用例的宏,屬性或者函數
斷定庫, 用于測試是否可以通過
輔助庫,如hook庫(測試前后調用某些函數或者方法),異常檢查(某些函數在某些參數的情況下拋出異常), 輸入組合(支持多排列的參數輸入組合)等。
支持IDE的集成
下面就按照官方文檔的順序來簡明扼要的

安裝與初步的使用

在控制臺窗口中執行下列命令:

$ npm install -g mocha$ mkdir test$ $EDITOR test/test.js

可以寫如下代碼:

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(5));   assert.equal(-1, [1,2,3].indexOf(0));  }); });});

回到控制臺:

$ mocha . ✔ 1 test complete (1ms)

這里mocha會查找當前文件目錄下test文件夾下的內容,自動執行。

斷定庫

這個是判定測試用例是否通過,默認下可以用nodejs的assert庫,與此同時,Mocha支持我們使用不同的斷定庫,現在可以支持下面的斷定庫,每個斷定庫的用法有一些差異,自己可以參考相應的文檔。

1 should.js(https://github.com/shouldjs/should.js) BDD style shown throughout these docs (BDD模式,本文檔用的都是這個斷定庫)
2 better-assert(https://github.com/tj/better-assert) c-style self-documenting assert()(C-模型下的斷定庫)
3 expect.js (https://github.com/Automattic/expect.js)expect() style assertions (expect模式的斷定庫)
4 unexpected(http://unexpected.js.org/) the extensible BDD assertion toolkit
5 chai(https://github.com/chaijs) expect(), assert() and should style assertions

同步代碼

同步代碼表示測試的是同步函數,上面的Array相關的例子代碼就是。這個比較好理解。

異步代碼

只所以有異步代碼測試,原因是在nodejs上許多異步函數,如下面的代碼中,只有done()函數執行完畢后,該測試用例才算完成

describe('User', function() { describe('#save()', function() {  it('should save without error', function(done) {   var user = new User('Luna');   user.saveAsync(function(err) {    if (err) throw err;    done(); // 只有執行完此函數后,該測試用例算是完成。   });  }); });});

詳解describe和it

上面的實例代碼比較簡單,那么什么是describe和it呢? 大致上,我們可以看出describe應該是聲明了一個TestSuit(測試集合) ,而且測試集合可以嵌套管理,而it聲明定義了一個具體的測試用例。 以bdd interface為例,具體的源代碼如下:

  /**   * Describe a "suite" with the given `title`   * and callback `fn` containing nested suites   * and/or tests.   */  context.describe = context.context = function(title, fn) {   var suite = Suite.create(suites[0], title);   suite.file = file;   suites.unshift(suite);   fn.call(suite);   suites.shift();   return suite;  };   /**   * Describe a specification or test-case   * with the given `title` and callback `fn`   * acting as a thunk.   */  context.it = context.specify = function(title, fn) {   var suite = suites[0];   if (suite.pending) {    fn = null;   }   var test = new Test(title, fn);   test.file = file;   suite.addTest(test);   return test;  };

Hooks(鉤子)

實際上這個在寫unit test是很常見的功能,就是在執行測試用例,測試用例集合前或者后需要某個回調函數(鉤子)。Mocha提供了before(),after(), beforeEach() 和aftetEach(),示例代碼如下:

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

hooks還有下列其他用法:

Describing Hooks - 可以對鉤子函數添加描述,能更好的查看問題
Asynchronous Hooks (異步鉤子): 鉤子函數可以是同步,也可以是異步的,和測試用例一下,下面是異步鉤子的示例代碼:

 beforeEach(function(done) {  // 異步函數  db.clear(function(err) {   if (err) return done(err);   db.save([tobi, loki, jane], done);  }); });

Root-Level Hooks (全局鉤子) - 就是在describe外(測試用例集合外)執行,這個一般是在所有的測試用例前或者后執行。
Pending Tests (掛起測試)

就是有一些測試,現在還沒有完成,有點類似TODO, 如下面的代碼:

describe('Array', function() { describe('#indexOf()', function() {  // pending test below 暫時不寫回調函數  it('should return -1 when the value is not present'); });});

Exclusive Tests (排它測試)

排它測試就是允許一個測試集合或者測試用例,只有一個被執行,其他都被跳過。如下面測試用例集合:

describe('Array', function() { describe.only('#indexOf()', function() {  // ... });   // 測試集合不會被執行  describe('#ingored()', function() {  // ... });});

下面是對于測試用例:

describe('Array', function() { describe('#indexOf()', function() {  it.only('should return -1 unless present', function() {   // ...  });   // 測試用例不會執行  it('should return the index when present', function() {   // ...  }); });});

需要說明的是,對于Hooks(回調函數)會被執行。

Inclusive Tests(包含測試)

與only函數相反,skip函數,將會讓mocha系統無視當前的測試用例集合或者測試用例,所有被skip的測試用例將被報告為Pending。
下面是對與測試用例集合的示例代碼:

describe('Array', function() {  //該測試用例會被ingore掉  describe.skip('#indexOf()', function() {  // ... });  // 該測試會被執行  describe('#indexOf()', function() {  // ... });});

下面例子是對具體的測試用例:

describe('Array', function() { describe('#indexOf()', function() {   // 測試用例會被ingore掉  it.skip('should return -1 unless present', function() {   // ...  });   // 測試用例會被執行  it('should return the index when present', function() {   // ...  }); });});

Dynamically Generating Tests(動態生成測試用例)

其實這個在很多其他的測試工具,如NUnit也會有,就是將測試用例的參數用一個集合代替,從而生成不同的測試用例。下面是具體的例子:

var assert = require('assert');function add() { return Array.prototype.slice.call(arguments).reduce(function(prev, curr) {  return prev + curr; }, 0);}describe('add()', function() { var tests = [  {args: [1, 2],    expected: 3},  {args: [1, 2, 3],  expected: 6},  {args: [1, 2, 3, 4], expected: 10} ]; // 下面就會生成三個不同的測試用例,相當于寫了三個it函數的測試用例。 tests.forEach(function(test) {  it('correctly adds ' + test.args.length + ' args', function() {   var res = add.apply(null, test.args);   assert.equal(res, test.expected);  }); });});

Interfaces(接口)

Mocha的接口系統允許用戶用不同風格的函數或者樣式寫他們的測試用例集合和具體的測試用例,mocha有BDD,TDD,Exports,QUnit和Require 風格的接口。

BDD - 這個是mocha的默認樣式,我們在本文中的示例代碼就是這樣的格式。
其提供了describe(), context(), it(), before(), after(), beforeEach(), and afterEach()的函數,示例代碼如下:

 describe('Array', function() {  before(function() {   // ...  });  describe('#indexOf()', function() {   context('when not present', function() {    it('should not throw an error', function() {     (function() {      [1,2,3].indexOf(4);     }).should.not.throw();    });    it('should return -1', function() {     [1,2,3].indexOf(4).should.equal(-1);    });   });   context('when present', function() {    it('should return the index where the element first appears in the array', function() {     [1,2,3].indexOf(3).should.equal(2);    });   });  }); });

TDD - 提供了 suite(), test(), suiteSetup(), suiteTeardown(), setup(), 和 teardown()的函數,其實和BDD風格的接口類似(suite相當于describe,test相當于it),示例代碼如下:

suite('Array', function() { setup(function() {  // ... }); suite('#indexOf()', function() {  test('should return -1 when not present', function() {    assert.equal(-1, [1,2,3].indexOf(4));  }); });});

Exports - 對象的值都是測試用例集合,函數值都是測試用例。 關鍵字before, after, beforeEach, and afterEach 需要特別定義。
具體的示例代碼如下:

module.exports = { before: function() {  // ... }, 'Array': {  '#indexOf()': {   'should return -1 when not present': function() {    [1,2,3].indexOf(4).should.equal(-1);   }  } }};

QUnit - 有點像TDD,用suit和test函數,也包含before(), after(), beforeEach()和afterEach(),但是用法稍微有點不一樣, 可以參考下面的代碼:

function ok(expr, msg) { if (!expr) throw new Error(msg);}suite('Array');test('#length', function() { var arr = [1,2,3]; ok(arr.length == 3);});test('#indexOf()', function() { var arr = [1,2,3]; ok(arr.indexOf(1) == 0); ok(arr.indexOf(2) == 1); ok(arr.indexOf(3) == 2);});suite('String');test('#length', function() { ok('foo'.length == 3);});

Require - 該接口允許我們利用require關鍵字去重新封裝定義 describe ,it等關鍵字,這樣可以避免全局變量。
如下列代碼:

var testCase = require('mocha').describe;var pre = require('mocha').before;var assertions = require('mocha').it;var assert = require('assert');testCase('Array', function() { pre(function() {  // ... }); testCase('#indexOf()', function() {  assertions('should return -1 when not present', function() {   assert.equal([1,2,3].indexOf(4), -1);  }); });});

上述默認的接口是BDD, 如果想使用其他的接口,可以使用下面的命令行:

mocha -ui  接口(TDD|Exports|QUnit...)

Reporters (測試報告/結果樣式)

Mocha 支持不同格式的測試結果暫時,其支持 Spec, Dot Matrix,Nyan,TAP…等等,默認的樣式為Spec,如果需要其他的樣式,可以用下列命令行實現:

mocha --reporter 具體的樣式(Dot Matrix|TAP|Nyan...)

Editor Plugins

mocha 能很好的集成到TextMate,Wallaby.js,JetBrains(IntelliJ IDEA, WebStorm) 中,這里就用WebStorm作為例子。 JetBrains提供了NodeJS的plugin讓我們很好的使用mocha和nodeJs。 添加mocha 的相關的菜單,具體配置過程可以參考https://www.jetbrains.com/webstorm/help/running-mocha-unit-tests.html

這里就可以直接在WebStorm中運行,調試mocha的測試用例了。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 诏安县| 农安县| 枞阳县| 伊春市| 于田县| 开阳县| 巴彦县| 钦州市| 巴中市| 乌鲁木齐市| 兴业县| 溆浦县| 博爱县| 闵行区| 大港区| 马尔康县| 都匀市| 遂昌县| 洱源县| 萝北县| 江安县| 噶尔县| 乌兰浩特市| 宾阳县| 西充县| 永靖县| 苗栗县| 柯坪县| 六枝特区| 名山县| 东山县| 宿松县| 科技| 新巴尔虎左旗| 钟祥市| 木里| 鸡泽县| 望江县| 准格尔旗| 西华县| 喜德县|