rabbitco rabbitco - 18 days ago 4
Javascript Question

Rewire: How is it possible for this function to execute without returning the specified return value

I am using the Rewire package to inject mocks in connection with doing unit testing. I was hoping to be able to test private functions in my modules:

var a = 10;
var b = 20;

function adder (){ //not exported
console.log(a);
console.log(b);
return a + b;
};


by doing this:

var rewire = require('rewire'),
md = rewire('./module'),
mock = {a: 30, b: 40},
cb = md.__get__('adder');

console.log(md.__with__(mock)(cb));


which logs the following to the console:

30
40
undefined


I find this strange because the logging of the
30
and
40
seems to indicate that
adder()
has successfully been invoked with the
mock
.

But why is the return value
undefined
in stead of
70
?

Answer

It looks to me that the callback function returned by rewire does not return a value unless it's a promise (in which case it returns the promise).

md.__with__(mock) returns a function that takes a callback, so it can be boiled down to something like this: function(callback){ callback(); }

and because that function returned by __with__() does not return the result of the callback, you end up with undefined in your console log. In other words, you're logging the result of the function returned by the mock instead of the return value of the callback passed to the mock.

Edit...Try this as proof:

md.__with__(mock)(function(){ console.log(cb());});

Here we'll be logging the value of the return value of cb (adder) instead of the undefined return from the callback.