使用 Nodejs 和 Expresso 进行 Rethinkdb

问题描述 投票:0回答:1

我正在尝试使用

rethinkdb
并通过
expresso
进行测试。我有功能

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;
});

我正在这样测试

  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");
        });
        
    }
  };

我正在运行这样的代码

expresso db.test.js 

但是即使出现错误,expresso也会显示

error 100% 1 tests
。 我尝试将
throw err;
放入
catch
,但没有任何变化。

但是如果我将

assert.eql(1, 2, "error");
放在
setup()
的开头,它会按预期失败;

有什么东西可以捕获错误吗?我怎样才能让它失败呢? 对于

sequelize
我发现了

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

rethink db 有类似的东西吗?

node.js rethinkdb expresso
1个回答
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');
        });
    }
  };

摩卡 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 驱动程序会返回所有操作的承诺。

module.exports.setup = function() {
    return r.connect({host: dbConfig.host, port: dbConfig.port });
});
© www.soinside.com 2019 - 2024. All rights reserved.