Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Mock external dependency

Mock external dependency



couchdb = require('couchdb');

exports.create = function(req, res){

  user = req.body

  if( validate(user) ) {


  } else {

    //render new again with the user



I want to test if the above Function created a user.


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.

Problem courtesy of: Pickels


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:

Second one I found is to load the file with a custom file loader and replace modules that way. It's explain here:

Solution courtesy of: Pickels


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Mock external dependency


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription