Mocha

Mocha

https://mochajs.org/#installationhtml

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases. Hosted on GitHub.node

 

Assert API

https://nodejs.org/api/assert.htmlgit

 

 

Describe it

https://cnodejs.org/topic/516526766d38277306c7d277web

如下爲最簡單的一個mocha示例:api

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)); }) }) });
  • describe (moduleName, testDetails) 由上述代碼可看出,describe是能夠嵌套的,好比上述代碼嵌套的兩個describe就能夠理解成測試人員但願測試Array模塊下的#indexOf() 子模塊。module_name 是能夠隨便取的,關鍵是要讓人讀明白就好。
  • it (info, function) 具體的測試語句會放在it的回調函數裏,通常來講info字符串會寫指望的正確輸出的簡要一句話文字說明。當該it block內的test failed的時候控制檯就會把詳細信息打印出來。通常是從最外層的describe的module_name開始輸出(能夠理解成沿着路徑或者遞歸鏈或者回調鏈),最後輸出info,表示該指望的info內容沒有被知足。一個it對應一個實際的test case
  • assert.equal (exp1, exp2) 斷言判斷exp1結果是否等於exp2, 這裏採起的等於判斷是== 而並不是 === 。即 assert.equal(1, ‘1’) 認爲是True。這只是nodejs裏的assert.js的一種斷言形式,下文會提到一樣比較經常使用的should.js。

若是exp1和exp2均爲字符串,字符串比較出錯時則控制檯會用顏色把相異的部分標出來。app

 

Hooks

https://mochajs.org/#hooksless

 

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

Tests can appear before, after, or interspersed with your hooks. Hooks will run in the order they are defined, as appropriate; all before() hooks run (once), then any beforeEach() hooks, tests, any afterEach() hooks, and finally after() hooks (once).async

 

本身動手

https://github.com/fanqingsong/code-snippet/tree/master/web/mocha_test函數

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

 

 

與TDD區別

https://stackoverflow.com/questions/4395469/tdd-and-bdd-differences

27 down vote

BDD is from customers point of view and focuses on excpected behavior of the whole system.

TDD is from developpers point of view and focuses on the implementation of one unit/class/feature. It benefits among others from better architecture (Design for testability, less coupling between modules).

From technical point of view (how to write the "test") they are similar.

I would (from an agile point of view) start with one bdd-userstory and implement it using TDD.

相關文章
相關標籤/搜索