Stub module function called from the same module

I was a bit wary of using exports since it's a bit magical (for instance when you're coding in Typescript, you never use it directly), so I'd like to propose an alternate solution, which still requires modifying the source code unfortunately, and which is simply to wrap the function to be stubbed into an object:

export const fooWrapper = {
    foo() {...}
}

function bar () {
    return fooWrapper.foo()
}

And sinon.stub(fooWrapper, 'foo'). It's a bit a shame having to wrap like that only for testing, but at least it's explicit and type safe in Typescript (contrary to to exports which is typed any).


I just tested this. And it works like charm.

'use strict'

function foo () {
  return 'foo';
}

exports.foo = foo;

function bar () {
  return exports.foo(); // <--- notice
}

exports.bar = bar;

Explanation

when you do sinon.stub(myModule, 'foo').returns('foo2') then sinon stubs the exported object's foo not the actually foo function from inside your myModule.js ... as you must know, foo is in accessible from outside the module. So when you set exports.foo, the exported object exports.foo stores the ref of foo. and when you call sinon.stub(myModule, 'foo').returns('foo2'), sinon will stub exports.foo and not the actual foo

Hope this makes sense!

Tags:

Node.Js