Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to mock object created via require

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();
        });
    });
like image 744
BaltoStar Avatar asked Nov 11 '22 09:11

BaltoStar


1 Answers

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 });
like image 78
Esteban Avatar answered Nov 15 '22 05:11

Esteban