我为 Node.js 编写了自己的瘦 mongodb 包装器,以消除代码重复。
但是,我在使用 Mocha 和 Should 运行异步单元测试时遇到问题。
发生的情况是,Should 库抛出的任何异常都会被 MongoDB 驱动程序而不是 Mocha 捕获。
也就是说,Mocha 既没有捕获错误,也没有调用 done() 函数。因此,Mocha 会打印出错误 Error: timeout of 2000ms超过
。
包装模块的片段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);
});
};
Mocha 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();
});
});
});
有什么办法可以解决这个问题吗?必须有一种方法来测试此类代码。
最佳答案
一次偶然的机会我发现了a GitHub fork处理不同的问题,但代码让我意识到我可以使用一个简单的技巧让 Mocha 捕获断言异常:
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
block 中,并在 catch 部分中调用 done(err)
完全符合预期:
- 如果没有发生断言错误,测试成功通过
- 由于
done()
函数接受错误参数,因此在断言错误的情况下测试失败
关于javascript - 如何测试自己的 mongodb 包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18417445/