dimanche 22 mars 2015

Closing a mongoose connection in an 'after()' testing clause

I have a testing script in which I have some setting up and tearing down before and after the tests run, which involves database connection and disconnection. Within the before clause is code which looks something along these lines (schema and other definitions omitted):



mongoose.connect(mongooseUri, function() {
var db = mongoose.connection;
...
post1.save(function(err, contents) {
testArray.push(contents);
});
done();
});


Within the actual tests, I write, read, and update contents of the testing database.

After the tests, I have an 'after()' clause within which is the following:



mongoose.connection.db.dropCollection("Posts", function(err, result) {
mongoose.disconnect();
done();
});


The tests end up 'hanging' and although the collection is successfully cleaned out (and code within the callback is run), I never get to see the reason for the failing tests (actual vs expected), and other information that is presented after my tests finish normally. I also have to manually kill gulp if I want to run the tests again. Furthermore, when messing around with the preparatory code after running some previous tests, using the mongoose.createConnection() route, I get an error message stating that I cannot open the connection as it is already open.


I have tried a number of other methods to kill the connection, including the following:



mongoose.close();
mongoose.db.close();
mongoose.connection.close();
mongoose.connection.db.close();
mongoose.disconnect();
mongoose.db.disconnect();
mongoose.connection.disconnect();
mongoose.connection.db.disconnect();


I have also tried:



  • Ditching the after() clause and manually setting a timeout of 5-30 seconds, within which I call mongoose.close() or the like.

  • Assigning my connection to a variable when I establish it in the before() clause, so I can reference it in after().

  • Creating a callback in before() with .close() (and the above variations) and running it in after() the connection.

  • Disconnecting within before() (which works).


Strangely, maybe 1/100 times, the test will finish as intended, but it doesn't seem to follow any pattern. All I want to do is kill the connection but it seems like it doesn't want to die. The part that particularly baffles me is that the connection refuses to be closed even if I write the code in a setTimeout(). It's like anywhere outside of the before() block, the db won't die. Any help is appreciated.


If it helps, I'm using lab for my tests.


Aucun commentaire:

Enregistrer un commentaire