Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding functions in other modules in node.js

I'm trying to stub a function with nodeunit in a Node.js app. Here's a simplified version of what I'm trying to do:

In lib/file.js:

var request = require('request');

var myFunc = function(input, callback){
    request(input, function(err, body){
        callback(body);
    });
};

In test/test.file.js:

var file = require('../lib/file');

exports['test myFunc'] = function (test) {
    request = function(options, callback){
        callback('testbody');
    };

    file.myFunc('something', function(err, body){
        test.equal(body, 'testbody');
        test.done();
    });
};

It seems like I'm not overriding request properly, because when I try to run the test, the actual non-stub request is getting called, but I can't figure out what the correct way to do it is.

EDIT:

To expand on Ilya's answer below, with my example above.

in lib/file/js:

module.exports = function(requestParam){
    return {
        myFunc: function(input, callback){
            requestParam(input, function(err, body){
                callback(body);
            });
        }
    }
}

Then in test/test.file.js:

var fakeRequestFunc = function(input, callback){
// fake request function
}

var file = require('../lib/file')(fakeRequestFunc)(
//test stuff
}
like image 848
Joe Avatar asked Feb 28 '26 13:02

Joe


1 Answers

As you noticed, variables declared in one module, cannot easily be accessed from another module. In such cases, you have two common variants:

1) Declare everything you need in every module (not your case, I suppose)

2) Pass parameters to a function

var ab = "foo",
index = require('/routes/index')(ab);

When you call a function form a module, you may pass it 'request' or any other vars or object you need.

like image 128
f1nn Avatar answered Mar 02 '26 02:03

f1nn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!