【问题标题】:Mocha js before hook and require not executing properly钩子之前的 Mocha js 并且需要不正确执行
【发布时间】:2016-07-16 06:24:52
【问题描述】:

我正在为一个项目编写单元测试,数据库模块是独立的(它建立与数据库的连接并具有批量插入方法)。我的单元测试文件中的代码如下:

var database = require('./db.js');  //once the database is connected there is a log saying connected to the database 
var Data = database.model;  //module export for the model 

before(function(){
    
    console.log("We are in the before hook");
    for(var i = 1; i <= 10; i++){

      var startDate = new Date(2016,1,1,0,0,0,0);
      var endDate = new Date(2016,1,1,1,0,0,0);

      var data = test_data.genIncreasing('Watch_'+i , startDate.getTime(), endDate.getTime() , 2000, 9); //will get around 3600 points
      console.log('Inserting ' + data.length + ' datapoints into database');  
      database.bulkInsert(data, function(err, data){
          if(err){
            Should.fail('Could not insert data into data base');
          }else{
            console.log('Inserted Watch_' + i + ' data into database');
          }
      });
     }
});

现在我期待在我的控制台中看到

Mongoose 默认连接打开到 DB-URI

紧随其后

我们在前面的钩子里

将 1800 个数据点插入数据库

将 1800 个数据点插入数据库 [10 次]

但我明白了

我们在前面的钩子里

将 1800 个数据点插入数据库

将 1800 个数据点插入数据库 [10 次]

紧随其后

Mongoose 默认连接打开到:DB_URI

我做了一些搜索,发现要求是同步的,mocha 单元测试也是如此。我在这里想念什么?你能告诉我正在发生的事情吗?

【问题讨论】:

  • 我假设你之前在 describe?
  • 不,它在外面,但是当我把它放在描述中时,我得到了相同的结果
  • 可能是db.js中的连接是懒惰的?
  • 对不起,你说 db.js 很懒是什么意思?

标签: node.js mongodb unit-testing mocha.js


【解决方案1】:

可能是 db.js 中的连接是惰性的? – Petr Mar 28 at 21:56

懒惰的意思是如果在你的 db.js 文件中你有这样的东西:

mongoose.connect('mongodb://localhost/stack');

这不是同步的,只是一个挂起的连接。你可以抓取连接并监听 open 事件:

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
});

在此事件触发之前,连接尚未准备好。

另一方面,mocha 可以处理同步和异步代码。但是由于你有回调,你的代码是异步的,所以你必须添加 done 回调。

describe('User', function() {
  describe('#save()', function() {
    it('should save without error', function(done) {
      var user = new User('Luna');
      user.save(function(err) {
        if (err) throw err;
        done();
      });
    });
  });
});

在这种情况下,完成回调位于 it 部分,但它对所有钩子的工作方式相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    • 2017-08-02
    • 2021-12-22
    • 1970-01-01
    • 2020-06-05
    相关资源
    最近更新 更多