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();
});
});
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With