Nick Nick - 1 year ago 67
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 });

assert(stub.calledOnce, true);

Answer Source

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.

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