2

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

4

3 回答 3

2

在你的 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);
    });
});
于 2013-11-09T06:14:35.343 回答
0

好的-非常接近。我必须做的是删除 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() 调用,它可以用于所有测试。

于 2013-11-10T00:32:21.220 回答
0
// 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();
            });

    });
于 2017-03-29T14:54:27.527 回答