【问题标题】:Mongoose open connection issue with SupertestSupertest 的 Mongoose 开放连接问题
【发布时间】:2013-11-09 06:03:05
【问题描述】:

我无法运行多个 Supertest/Mocha 测试,因为我收到一个错误 Error: Trying to open unclosed connection. - 我发现这个 post 建议循环和检查连接状态。想知道有没有更好的方法?也许最近在 Supertest 中添加了一些东西来处理这个问题。

【问题讨论】:

  • 您不必为每个测试打开一个新连接,只需在测试的顶层连接一次并重新使用该连接。

标签: javascript node.js mongoose supertest


【解决方案1】:

在你的 Mocha 测试中添加一个 before 函数来像这样连接到 MongoDB

var mongoose = require('mongoose');

describe('My test', function() {
    before(function(done) {
       if (mongoose.connection.db) return done();
       mongoose.connect('mongodb://localhost/puan_test', done);
    });
});

【讨论】:

【解决方案2】:

好的 - 非常接近。我必须做的是删除 describe 方法调用,并将 before() 调用放在一个公共文件中以用于所有测试 - 超级测试或直接 mocha 单元测试。

var db;

// Once before all tests - Supertest will have a connection from the app already while others may not
before(function(done) {
  if (mongoose.connection.db) {
    db = mongoose.connection;
    return done();
  }
  db = mongoose.connect(config.db, done);
});

// and if I wanted to load fixtures before each test
beforeEach(function (done) {
  fixtures.load(data, db, function(err) {
    if (err) throw (err);
    done();
  })
});

通过省略上面的 describe() 调用,它可以用于所有测试。

【讨论】:

    【解决方案3】:
    // Also you can use the 'open' event to call the 'done' callback
    // inside the 'before' Mocha hook.
    
        before((done) => {
            mongoose.connect('mongodb://localhost/test_db');
            mongoose.connection
                .once('open', () => {
                    done();
                })
                .on('error', (err) => {
                    console.warn('Problem connecting to mongo: ', error);
                    done();
                });
    
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-10
      • 2019-11-23
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多