I have a function called connectToMongo that connects to a locally-running mongodb database myapp. I have another function which invokes connectToMongo. I would like to test this other function with mocha. However, I would like to make it so that, while testing, any calls to connectToMongo will automatically connect to my myapp_test database instead of my normal one.
Ideally (I think) I'd like to do something like this (where connectToMongoTestingDatabase connects to myapp_test):
var connectToMongo = require('./connectToMongo'),
connectToMongoTestingDatabase = require('./connectToMongoTestingDatabase')
registerUser = require('./registerUser');
testingLibrary.configureAlternateBehavior(connectToMongo, connectToMongoTestingDatabase);
it('should register a user', function (done) {
registerUser({name: 'bob', password: 'password1'}, function (error, response) {
connectToMongoTestingDatabase(function (error, database) {
database.collection('users').findOne({name: 'bob'}, function (error, user) {
expect(user).not.to.be.null;
done();
});
});
});
});
I have been trying to make sense of the Sinon.JS library. I can't tell whether spies, stubs or mocks would fulfill this need, nor what the equivalent of testingLibrary.configureAlternateBehavior would be.
I suppose I could also create some global variable called global.MYAPP_TESTING, set that to true before I start my tests, and in the implementation of connectToMongo I could connect to the myapp_test database if global.MYAPP_TESTING is true. That seems bad though.
What is the best way to substitute the behavior of one function for another in JavaScript unit testing?
require()in place of the mongo business.