NodeJS mocking with proxyquire

I recently stumbled upon proxyquire (https://github.com/thlorenz/proxyquire), which is a mocking framework for NodeJS’s require. It basically gives you the possibility to stub out externally required dependencies of your module under test.

An example would be, if you use a library such as mongoose (https://github.com/learnboost/mongoose/), where you have code like the following in your modules:


    var mongoose = require('mongoose'),
        Product = mongoose.model('Product'),
 
    findAllProducts = function() {
        Product.find({}, function(err, products) {
            // do something with the product
        };
    };
    
    module.exports.findAllProducts = findAllProducts;

So, basically, you just have the concept of a Mongo model, which is used to find some records in MongoDB. Of course, when writing a Unit Test, you don’t want the test to actually go to the database, instead you want to “fake” what Product.find() does. Proxyquire can help with that.

It can be easily installed and setup using


npm install --save-dev proxyquire

in your project root.

Then, just add


var proxyquire = require('proxyquire');

to the top of your test file.

Mocking out a dependency is very straightforward as well, in the test:


  describe('productmodule', function() {
      var productmodule,
          mongooseStub;
 
      before(function() {
          mongooseStub = {
              model: function() {
                  return {
                      find: function(query, callback) {
                          callback(); 
                      } 
                  };
              } 
          };
 
          productmodule = proxyquire('../modules/product', {'mongoose': mongooseStub});
      });

  });

What is important here is, that the path for the module under test, is the path from the test to the module, whereas the path to the stubbed out module is the same path that is used in the module under test. Every dependency, which is not explicitly mocked out is the real thing.

As for the mocking, you can do just about whatever you want to do here, even use something like SinonJS (http://sinonjs.org/) to spy on one of the mocked out methods.

If you’re interested in some more examples, there are plenty on the project’s GitHub page, which can be found here

I hope this helps you test some of your awesome NodeJS apps 😉

~m

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>