I'm using the grunt-mocha-test
package to run my unit tests in Node. Here's how the config object for grunt-mocha-test
looks in my gruntfile:
mochaTest: {
src: watchFiles.serverTests,
options: {
reporter: 'spec',
require: 'server.js'
}
}
watchFiles.serverTests
is an array of file paths. server.js
bootstraps my app. In server.js
, I have something like the following:
var db = mongoose.connect(config.db, function(err) {
// Setup express, etc. here
// Set module exports
});
Previously, that looked something like this:
var db = mongoose.connect(config.db);
// Setup express, etc. here (some of which reference db)
// Set module exports
The problem was that Express needed the database connection to be successfully in order for it to initialize properly. Without the async database connection, I was getting some strange errors. So, I switched to the async setup. Now, however, when I require server.js
with the async calls inside, the test runner fires off the Mocha tests before the app is completely fired up. Because of this, I need to find a happy medium along these lines:
var db = mongoose.connect(config.db, function(err) {
// Setup express, etc. here
// Set module exports
});
// Do something here that waits for the above to complete,
// so that the module is loaded synchronously.
As an alternative, I can pass a function to the mochaTest
config object. Is there a way I could create this behavior there?
You could use a before
Function with the done
-Callback. This will halt your tests until done
is called. Inside the before
-Function you can then listen on mongoose connected
-Event. Something like this:
var mongoose = require('mongoose');
before(function(done){
mongoose.connection.on('connected', done);
});
Then just place this before your first test.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.