rabbitco rabbitco - 1 year ago 71
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
return a + b;

by doing this:

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


which logs the following to the console:


I find this strange because the logging of the
seems to indicate that
has successfully been invoked with the

But why is the return value
in stead of

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download