A stub module function called from the same module

I can’t find a way to stub a function called inside the same module, this function is defined (the stub does not seem to work). Here is an example:

myModule.js:

'use strict' function foo () { return 'foo' } exports.foo = foo function bar () { return foo() } exports.bar = bar 

myModule.test.js:

 'use strict' const chai = require('chai') const sinon = require('sinon') chai.should() const myModule = require('./myModule') describe('myModule', () => { describe('bar', () => { it('should return foo', () => { myModule.bar().should.equal('foo') // succeeds }) describe('when stubbed', () => { before(() => { sinon.stub(myModule, 'foo').returns('foo2') // this stub seems ignored }) it('should return foo2', () => { myModule.bar().should.equal('foo2') // fails }) }) }) }) 

It reminds me of static Java functions that are not smooth (almost).

Any idea how to achieve what I'm trying to do? I know that foo fetching in another module will work, but that is not what I am trying to do here. I also know that calling foo in the bar method with the this will also work, I am puzzled by using this in this context (since I am not using OOP).

+7
source share
1 answer

I just experienced this. And it works like a charm.

 'use strict' function foo () { return 'foo'; } exports.foo = foo; function bar () { return exports.foo(); } exports.bar = bar; 

Explanation

when you execute sinon.stub(myModule, 'foo').returns('foo2') and then sinon exported object foo not the actual foo function inside your myModule.js ... as you should know, foo is accessible from outside the module. Therefore, when you install exports.foo , the exported exports.foo object saves ref foo . and when you call sinon.stub(myModule, 'foo').returns('foo2') , sinon will drown exports.foo , not the actual foo

Hope this makes sense!

+7
source share

All Articles