Rethinkdb with nodejs and expresso

时间:2015-06-15 15:04:18

标签: node.js rethinkdb expresso

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 个答案:

答案 0 :(得分:3)

问题是此测试是异步的,您将其视为同步测试。您需要执行以下操作:

  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

您应该考虑查看mocha.js,它通过传递done函数为异步操作提供了更好的API。相同的测试看起来像这样:

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

<强>承诺

您编写的第一个函数可以通过以下方式重写,因为默认情况下,RethinkDB驱动程序会在所有操作中返回一个promise。

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