如何使用gulp mocha进行测试时如何创建mongoose连接

时间:2015-04-28 23:10:19

标签: mongoose gulp mocha

我想做一个gulp任务,用一个命令用mocha运行我的所有测试。 (我的测试需要使用mongoose连接到DB)

然后我收到了这个错误: { [Error: Trying to open unclosed connection.] state: 1 }

经过一番研究,我发现这篇文章:  Mongoose Trying to open unclosed connection

它说我应该使用createConnection()而不是' connect()`。

现在的问题是:

我如何使用beforeafter进行测试,在完成每个测试用例之前,如何在db连接后调用done < / p>

1 个答案:

答案 0 :(得分:0)

以下是我的gulp任务:

gulp.task('mocha', function () {
  var testFile = argv['f'];
  var fullPaths;
  if (testFile) {
    fullPaths = paths.server + 'tests/' + testFile;
  } else {
    fullPaths = serverUnitTestFiles;
  }
  var dbConnectionModulePath = paths.server + 'tests/db-connection.js';
  var dbConnection = gulp.src(dbConnectionModulePath, { read: false });
  var tests = gulp.src(fullPaths, { read: false });
  return series(dbConnection, tests)
      .pipe(mocha({ reporter: 'nyan' }));
});

这是db-connection.js模块:

'use strict';

var mongoose = require('mongoose'),
    connection = mongoose.connection,
    dbName = 'learnMongo';

before(function (done) {
  connection.on('error', console.error);
  connection.once('open', function () {
    done();
  });
  mongoose.connect('mongodb://localhost:27017/' + dbName);
});

after(function (done) {
  connection.close(done);
});