Hao Hao - 14 days ago 6
Javascript Question

When unit testing with Jasmine, how to require a file without 'sub-requires'?

let's say in my spec I write the follow,

const moduleA = require('moduleA');


... and in moduleA it will require another module say 'moduleB'

In my opinion unit testing should be separate, and all dependencies should be mocked. But I can't find a good way to require moduleA without requiring moduleB at the same time.

Any suggestions how this can be done? Thanks in advance.

Things I've tried:
rewirejs(https://github.com/jhnns/rewire), which seems nice but still needs to require moduleB before you can actually substitute moduleB

Answer

You can have your modules export a function that will take the dependency as an argument (instead of requiring it). So you'll have:

/*moduleA*/
module.export = function(depB){
    /*your code here*/
});

And when you import moduleA you do:

var moduleB = require('moduleB');
var moduleA = require('moduleA')(moduleB);

An alternative approach would be to pass a dependency tree to the submodule:

const platform = {
     moduleA : require('moduleA'),
     moduleB : require('moduleB'),
}

var moduleA = platform.moduleA(platform);

And in moduleA:

module.export = function(platform){
    var moduleB = platform.moduleB; //your dependency here
    //for consistency you'd also want to export a function that takes the depdency tree even if it doesnt take a dependency (so module configuration remains consistent across all your modules)
}

It would be very easy to replace the dependency for a mock this way. There is more on the subject here and here.

Comments