如何testing自己的MongoDB包装

我已经编写了自己的用于Node.js的瘦蒙哥包装,以消除代码重复。

但是,我在使用Mocha和Should运行asynchronousunit testing时遇到问题。

会发生什么情况是,由MongoDB驱动程序而不是Mocha捕获的应用程序库引发的任何exception。 也就是说,Mocha既不会捕获错误,也不会调用done()函数。 因此,摩卡打印出一个错误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(); }); }); }); 

有没有办法解决这个问题? 必须有方法来testing这样的代码。

只是偶然的运气,我发现了一个处理不同问题的GitHub fork ,但是这个代码让我意识到我可以用一个简单的技巧来让Mocha去捕捉断言exception:

 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块中,并在catch部分调用done(err)完全符合预期:

  1. 如果没有发生断言错误,则testing通过成功
  2. 由于done()函数接受错误参数,所以在断言错误的情况下testing失败