I am creating a connection (and cleaning up a database) with mongoose before running all tests with mocha like so (_setup.js):
var mongoose = require('mongoose'),
nconf = require('nconf');
nconf.env().argv();
var _conn;
before(function(done){
_conn = mongoose.createConnection(nconf.get('TEST_DB'), function(error){
if(error) return done(error);
_conn.db.dropDatabase(done);
});
});
after(function(done){
_conn.db.dropDatabase(function(error){
if(error) return done(error);
_conn.close(done);
});
});
Other test suites need this connection to build the mongoose models. I am using a separate connection instead of the default mongoose connection because these tests can be run in app through the mocha js api. The app uses the default mongoose connection. Example test needing connection variable:
var should = require('should'),
service = require('../lib/service')(_conn); // << somehow need that conn variable created in before tests
describe('Service', function(){
describe('#dodboperation()', function(){
//tests and stuff
Is there anyway to pass variables between files/test suites in mocha? Suggestions?
Use environment variables. At the top of your mocha file, include:
process.env.TEST = 'true'; // Use test database
Then, include use a database config like this one:
var url = require('url');
var config = {};
var dbUrl;
if (typeof(process.env.DATABASE_URL) !== 'undefined') {
dbUrl = url.parse(process.env.DATABASE_URL);
}
else if (process.env.TEST === 'true') {
dbUrl = url.parse('tcp://postgres:postgres@127.0.0.1:5432/test');
}
else {
dbUrl = url.parse('tcp://postgres:postgres@127.0.0.1:5432/db');
}
config.dialect = 'postgres';
config.protocol = dbUrl.protocol.substr(0, dbUrl.protocol.length - 1); // Remove trailing ':'
config.username = dbUrl.auth.split(':')[0];
config.password = dbUrl.auth.split(':')[1];
config.host = dbUrl.hostname;
config.port = dbUrl.port;
config.database = dbUrl.path.substring(1);
console.log('Using database ' + config.database);
module.exports = config;
We also run two different servers on different ports on our dev machines. We run nodemon on port 4000 for regular development, and then if TEST == 'true' the server runs on port 4500.