我在任何其他描述之前在after()调用中进行清理。如果所有测试都通过,清理工作就会完成。但是如果任何测试失败,清理代码将收到一个错误:[错误:没有打开连接]。
我认为mongodb回调中的断言会引发错误,导致连接关闭。 这让我感到困惑:
那么,即使断言失败,我还应该做些什么来清理工作呢?
我在下面做了一个示例代码:
var mongo = require('mongoskin')
, should = require('should')
;
describe('mongo', function() {
var db;
before(function() {
console.log('before');
db = mongo.db('devstack.local:27017/test')
});
after(function(done) {
console.log('after');
db.dropDatabase(function(err) {
should.not.exist(err);// [Error: no open connections]
db.close(done);
});
});
describe('close', function() {
it('should count!=0', function(done) {
db.collection('empty').count(function(err, count) {
count.should.not.equal(0); // use an empty collection to make sure this fail
done();
});
})
})
})
答案 0 :(得分:0)
这是一个假设:连接从不发生。
当我运行测试套件时:
db = mongo.db('nonexistent:3333/test')
而不是您拥有的地址,我可以完全重现您的错误。请注意:
count.should.not.equal(0);
失败,因为count
未定义,不是因为调用should
模块定义的任何框架。
如果我转换测试以便检查err
:
it('should count!=0', function(done) {
db.collection('empty').count(function(err, count) {
should.not.exist(err); // <<< This is where it fails now!
count.should.not.equal(0); // use an empty collection to make sure this fail
done();
});
});
然后,should.not.exist(err)
的测试失败,err
为:
[Error: failed to connect to [nonexistent:3333]]
有几点想法:
请务必在回调中查看err
。
在建立数据库连接的before
回调中,如果未建立连接,则至少执行一项保证失败的操作。你想要一个尽可能低廉的操作。我不太了解Mongo,但这似乎可以解决问题:
before(function (done) {
db = mongo.db(<put address here>, {safe: true});
db.open(function (err) {
should.not.exist(err);
done();
});
});
这样Mocha会立即检测到失败。