title: Replace a function with another function for testing
body: <p>I have a function called <code>connectToMongo</code> that connects to a locally-running mongodb database <code>myapp</code>. I have another function which invokes <code>connectToMongo</code>. I would like to test this other function with mocha. However, I would like to make it so that, while testing, any calls to <code>connectToMongo</code> will automatically connect to my <code>myapp_test</code> database instead of my normal one.</p>
  
  <p>Ideally (I think) I'd like to do something like this (where <code>connectToMongoTestingDatabase</code> connects to <code>myapp_test</code>):</p>
  
  <pre><code>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();
              });
          });
      });
  
  });
  </code></pre>
  
  <p>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 <code>testingLibrary.configureAlternateBehavior</code> would be.</p>
  
  <p>I suppose I could also create some global variable called <code>global.MYAPP_TESTING</code>, set that to <code>true</code> before I start my tests, and in the implementation of <code>connectToMongo</code> I could connect to the <code>myapp_test</code> database if <code>global.MYAPP_TESTING</code> is true. That seems bad though.</p>
  
  <p>What is the best way to substitute the behavior of one function for another in JavaScript unit testing?</p>