Nick Nick - 3 months ago 14
Node.js Question

How to stub/spy external methods in a module that are called internally?

//entity module
function isUnique(name) {
return true;
}
exports.isUnique = isUnique;

function create(name) {
if (isUnique(name)) { return console.log(name); }
else { return new Error(); }
}
exports.create = create;


Is it possible to stub the "isUnique" method to change the behavior of the "create" method?

var entity = require("./entity");
var sinon = require("sinon");
var assert = require("assert");

var stub = sinon.stub(entity, "isUnique", function (name) { return false });

entity.create("test");
stub.restore();
assert(stub.calledOnce, true);

Answer

In short: no.

Your module holds two references to the isUnique function: one from the function declaration itself, and one assigned to exports.isUnique.

The create function is using the first, but Sinon is stubbing the second.

For the stub to get called, create needs to use the reference that gets stubbed:

if (exports.isUnique(name)) { return console.log(name); }
// `this.isUnique` also works, because `this` === `module.exports`

Alternatively, you can use a module like rewire.