mongoskin+mocha: How to do clean-up in after() when assertion failed?

2k Views Asked by At

I do the clean-up in an after() call before any other describe. If all tests pass, the clean-up will do the job. But if any test fails, the clean-up code will receive an err: [Error: no open connections].

I think the assertion in the callback of mongodb throws an error cause the connection closed. That make me confusing:

  • First, I think the callback of mongodb is the right place to put some assertions;
  • Second, the assertions will throw error when failed, and cause connection closes;
  • Finally, the clean-up will failed due to connection closed.

So, what else should I do to make clean-up to do its job even the assertion failed?

I have made a sample code below:

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

There are 1 best solutions below

0
On

Here's an hypothesis: the connection never happens.

When I run your test suite with:

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

instead of the address you have, I can completely reproduce your error. Note that:

  1. count.should.not.equal(0); fails because count is undefined, not because any of the framework defined by the should module is called.

  2. If I transform the test so that it checks 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();
      });
    });
    

Then the test fails at should.not.exist(err) and err is:

[Error: failed to connect to [nonexistent:3333]]

A couple of thoughts:

  1. Always check err in your callbacks.

  2. In the before callback which establishes the database connection, perform at least one operation which is guaranteed to fail if the connection is not established. You'd want an operation which is as inexpensive to perform as possible. I don't know Mongo very well but this seems to do the trick:

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

    This way Mocha will detect the failure right away.