Answering myself. The solution is simple: for each driver, this is the test.js file:
var driver = require('./specificDriver'); var simpledblayerTests = require( "./lib/simpledblayer/test.js" );
var tests = simpledblayerTests.get(
function getDbInfo( done ) {
mw.connect('mongodb://localhost/tests', {}, function( err, db ){
if( err ){
throw new Error("MongoDB connect: could not connect to database");
} else {
done( null, db, driver );
}
});
},
function closeDb( db, done ) {
db.close( done );
}
);
for(var test in tests) {
exports[ test ] = tests[ test ];
}
Basically, the get()
function exported by the actual "main" module (more about this later) takes two parameters: two functions that open and close the database connection.
That get()
function returns a bunch of functions ready to be exported -- the functions that make up your unit testings.
The main module will have something like this:
exports.get = function( getDbInfo, closeDb ){
var tests;
var g = {};
var startup = function( test ){
var self = this;
test.doesNotThrow( function(){
getDbInfo( function( err, db, driver ){
if( err ){
throw( new Error("Could not connect to db, aborting all tests") );
process.exit();
}
// Set the important g.driver variables (db and driver)
g.db = db;
d.driver = driver
test.done();
});
});
}
var finish = function( test ){
var self = this;
closeDb( g.db, function( err ){
if( err ){
throw( new Error("There was a problem disconnecting to the DB") );
}
test.done();
});
};
tests = {
startup: startup,
// ...
// Your tests here. All functions will have access to g.db and g.driver
// ...
finish: finish
}
return tests;
}
This way, every single module will run the same tests. However, the driver
variable and the functions to connect/disconnect to the database will be simple.
See it in action with real code: