Rethinkdb with nodejs and expresso

191 Views Asked by At

I am trying to use rethinkdb and test it via expresso. I have function

module.exports.setup = function() {
  var deferred = Q.defer();
  r.connect({host: dbConfig.host, port: dbConfig.port }, function (err, connection) {
     if (err) return deferred.reject(err);
     else deferred.resolve();
  });
 return deferred.promise;
});

I am testing it like this

  module.exports = {
    'setup()': function() {
        console.log("in setup rethink");

        db.setup().then(function(){
            console.log(clc.green("Sucsessfully connected to db!"));
        }).catch(function(err){
            console.log('error');
            assert.isNotNull(err, "error");
        });

    }
  };

And I am runing code like this

expresso db.test.js 

But expresso shows error 100% 1 tests even in case of error. I tried to put throw err; in catch, but nothing changes.

But if I put assert.eql(1, 2, "error"); in the begining of setup() it fails as expected;

Is there something, that caches errors? How can I make it fail as it should be? For squalize I found

Sequelize.Promise.onPossiblyUnhandledRejection(function(e, promise) {
    throw e;
});

Is there something like this for rethink db?

1

There are 1 best solutions below

2
On BEST ANSWER

The problem is that this test is asynchronous, and you're treating it as a synchronous test. You need to do the following:

  module.exports = {
    'setup()': function(beforeExit, assert) {
        var success;
        db.setup().then(function(){
            success = true;
        }).catch(function(err){
            success = false;
            assert.isNotNull(err, "error");
        });

        beforeExit(function() {
            assert.isNotNull(undefined, 'Ensure it has waited for the callback');
        });
    }
  };

Mocha vs Express

You should consider taking a look at mocha.js, which has a much nicer API for asynchronous operations by passing the done function. The same test would look like this:

  module.exports = {
    'setup()': function(done) {
        db.setup().then(function(){
            assert.ok(true);
        }).catch(function(err){
            assert.isNotNull(err, "error");
        })
        .then(function () {
            done();
        });
    }
  };

Promises

The first function you wrote can be re-written in the following manner, because the RethinkDB driver, by default, returns a promise on all operations.

module.exports.setup = function() {
    return r.connect({host: dbConfig.host, port: dbConfig.port });
});