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();
});
});
});
模擬有什麼辦法來解決該問題?必須有方法來測試這樣的代碼。
難道真的沒有人有想法嗎?我試圖多次分析這個問題,但沒有找到任何解決辦法。這意味着我無法測試我的DB代碼:( –