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

Mock external dependency

Mock external dependency

Problem

//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.

Problem courtesy of: Pickels

Solution

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

Solution courtesy of: Pickels

Discussion

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

×