2013-08-24 49 views
1

我已經編寫了自己的用於Node.js的瘦蒙哥包裝來消除代碼重複。如何測試自己的mongodb包裝

但是,我在使用Mocha和Should運行異步單元測試時遇到問題。

會發生什麼情況是,應該由MongoDB驅動程序而不是Mocha捕獲任何拋出的異常。即,Mocha既不捕獲錯誤,也不調用done()函數。因此,Mocha打印出錯誤Error: timeout of 2000ms exceeded

封裝模塊的片段db.js

var mongodb = require('mongodb').MongoClient; 

exports.getCollection = function(name, callback) { 
    mongodb.connect(dbConfig.dbURI, {auto_reconnect: true}, function(err, db) { 
     if (err) 
      return callback(err, null); 

     db.collection(name, {strict: true}, callback); 
    }); 
}; 

摩卡test.js

var should = require('should'); 
var db  = require('./db.js'); 

describe('Collections', function() { 
    it.only('should retrieve user collection', function(done) { 
     db.getCollection('user', function(err, coll) { 
      should.not.exist(err); 
      coll.should.be.a('object'); 
      // HERE goes an assertion ERROR 
      coll.collectionName.should.equal('user123'); 

      done(); 
     }); 
    }); 
}); 

同樣的行爲可以通過這種簡單的test.js

var should = require('should'); 

var obj = { 
    call: function(callback) { 
     try { 
      console.log('Running callback(null);'); 
      return callback(null); 
     } 
     catch(e) { 
      console.log('Catched an error:', e); 
     } 
    } 
}; 

describe('Test', function() { 
    it('should catch an error', function(done) { 
     obj.call(function(err) { 
      should.exist(err); 
      done(); 
     }); 
    }); 
}); 

模擬有什麼辦法來解決該問題?必須有方法來測試這樣的代碼。

+0

難道真的沒有人有想法嗎?我試圖多次分析這個問題,但沒有找到任何解決辦法。這意味着我無法測試我的DB代碼:( –

回答

1

只需通過一個偶然的運氣,我看到a GitHub fork處理不同的問題,但這些代碼使我意識到,我可以用一個簡單的技巧,使摩卡趕上斷言例外:

describe('Test', function() { 
    it('should catch an error', function(done) { 
     obj.call(function(err) { 
      try { 
       should.exist(err); 
       done(); 
      } catch (err) { 
       done(err); 
      } 
     }); 
    }); 
}); 

即包裹should調用到try/catch塊和閉鎖段調用done(err)究竟是幹什麼的預期:如果沒有發生斷言錯誤

  • 測試中斷言錯誤感謝的情況下未能done()函數接受一個

    1. 測試順利通過錯誤參數