1

I want to make a gulp task to run all my tests with mocha with one single command. (My test need to connection to DB with mongoose)

Then I got this error: { [Error: Trying to open unclosed connection.] state: 1 }

After some research, I found this post: Mongoose Trying to open unclosed connection

It said I should use createConnection() instead of 'connect()`.

Here is the question now:

How could I use before and after for the test, and how could I call done after db connected before go through each test cases?

Community
  • 1
  • 1
Yushi
  • 93
  • 9
  • Are you running the `mongoose.connect()` command more than once, even across multiple test scripts? You should only ever need to execute the `connect` command one time. – Brian Shamblen Apr 28 '15 at 23:35
  • Yes, I run them in each test spec. The reason I did this is that I want to make it possible that I also can run each test spec separately while I can run them all in one time. If I can run `mongoose.connect() ` only once run each run, I think I need to work on some gulp script to make this possible. – Yushi Apr 29 '15 at 01:39

1 Answers1

0

Following is my gulp task:

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

And here is the db-connection.js module:

'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);
});
Yushi
  • 93
  • 9