mongoskin + mocha:当断言失败时,如何在after()中进行清理?

时间:2014-01-05 15:06:27

标签: node.js mongodb mocha mongoskin

我在任何其他描述之前在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();
      });
    })
  })
})

1 个答案:

答案 0 :(得分: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();
      });
    });
    
  3. 然后,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会立即检测到失败。