Q:

Mock external dependency

//user.js

couchdb = require('couchdb');

exports.create = function(req, res){

  user = req.body

  if( validate(user) ) {

    couchdb('db').insert(user);
    //redirect

  } else {

    //render new again with the user

  };

};

I want to test if the above function created a user. 
//user_spec.js

describe('User create', function(){

  beforeEach( function(){
    //call create with valid user
  });

  it('should create a user', function(){

    //test database for user
    assert( fakeDatabase.users.length, 1)

  });

})

Does anybody know a way to replace the couchdb object with a fake one so I can test if a user was created. I don't really want to be making calls to a real couchdb in my unit tests.

A:

Found a couple of solutions. The first one is to explicitly add dependencies to a module.
module.exports = function(dependency){
   var dependency = dependency | require('dependency');
};

Found this solution here: http://csausdev.wordpress.com/2010/12/17/dependency-injection-in-node-js/
Second one I found is to load the file with a custom file loader and replace modules that way. It's explain here: http://howtonode.org/testing-private-state-and-mocking-deps

