【发布时间】:2015-03-18 21:22:05
【问题描述】:
我正在使用 mongojs 并为 mocha 编写测试,并使用 istanbul 运行覆盖率。我的问题是我想包括测试数据库错误。
var mongojs = require('mongojs');
var db = mongojs.connect(/* connection string */);
var collection = db.collection('test');
...
rpc.register('calendar.create', function(/*... */) {
collection.update({...}, {...}, function (err, data) {
if (err) {
// this code should be tested
return;
}
// all is good, this is usually covered
});
});
测试看起来像这样
it("should gracefully fail", function (done) {
/* trigger db error by some means here */
invoke("calendar.create", function (err, data) {
if (err) {
// check that the error is what we expect
return done();
}
done(new Error('No expected error in db command.'));
});
});
有一个相当复杂的设置脚本来设置集成测试环境。当前的解决方案是使用db.close() 断开数据库并运行测试,从而导致所需的错误。当之后所有其他测试都需要数据库连接失败时,就会出现此解决方案的问题,因为我尝试重新连接但没有成功。
关于如何巧妙地解决这个问题的任何想法?最好不要编写下一个版本的mongojs 可能不会引发的自定义错误。或者有没有更好的方法来构建测试?
【问题讨论】:
标签: node.js testing mocha.js mongojs