0

在进行任何其他描述之前,我会在 after() 调用中进行清理。如果所有测试都通过了,清理工作就完成了。但是如果任何测试失败,清理代码将收到一个错误:[错误:没有打开的连接]。

我认为 mongodb 回调中的断言会引发错误,导致连接关闭。这让我很困惑:

  • 首先,我认为 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();
      });
    })
  })
})
4

1 回答 1

0

这是一个假设:连接永远不会发生。

当我运行您的测试套件时:

db = mongo.db('nonexistent:3333/test')

而不是您拥有的地址,我可以完全重现您的错误。注意:

  1. count.should.not.equal(0);失败count是因为未定义,而不是因为should调用了模块定义的任何框架。

  2. 如果我转换测试以使其检查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]]

几个想法:

  1. 始终检查err您的回调。

  2. before建立数据库连接的回调中,至少执行一个操作,如果连接不建立,则保证失败。您需要一个尽可能便宜的操作。我不太了解Mongo,但这似乎可以解决问题:

    before(function (done) {
      db = mongo.db(<put address here>, {safe: true});
      db.open(function (err) {
        should.not.exist(err);
        done();
      });
    });
    

    这样 Mocha 将立即检测到故障。

于 2014-01-06T14:49:23.113 回答