Question

I'm new to node.js and in most code I've seen I don't see IoC/DI style constructor injection of dependencies.

Instead, typically the node.js extension require() is used to create local vars allowing access to external modules' exports.

But when writing unit-tests ( that isolate single layer/function ), how to mock the modules accessed via vars created with require ?

/helpers/dataHelper.js

var dataModel = require('../models/dataModel.js');

var getFormattedDataForRegion = function(region, callback) {
    var data = {};
    // validate region
    // query dataModel
    // async.map format data items
    // callback(data);
}

/tests/dataHelperTests.js

describe('dataHelper', function(){

    it('getFormattedDataForRegion returns expected response', function(done){

        var expectedData = {};
        // populate expectedData

        // **** need some way to mock dataModel *****

        dataHelper.getFormattedDataForRegion("west", function(data){
            expect(data).to.eql(expectedData);
            done();
        });
    });
Was it helpful?

Solution

This is done with proxyquire.

I personally don't like the technique, but it's the best way that I've found to respect the "node way" and still be able to test easily. You'd do:

var proxyquire =  require('proxyquire'),
    dataModelMock = require('./mocks/dataModel');

proxyquire('path/to/helpers/dataHelper.js', { '../models/dataModel.js': dataModelMock });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top