A.js
const func2 = () => 'world';
module.exports = {func2}
Util.js
const {func2} = require("./A");
const func1 = () => {
return 'hello ' + func2(); // <= use the module
}
module.exports = { func1 }
Util.test.js
const sinon = require('sinon');
const {func1} = require('./util');
const a = require('./A');
const chai = require("chai");
const expect = chai.expect;
describe('func1', () => {
it('should work', () => {
const stub = sinon.stub(a, 'func2').returns('everyone');
expect(func1()).to.be.equal('hello everyone'); // Success!
});
});
Getting assertion failure... Sinon stub func2 is not stubbing
AssertionError: expected 'hello world' to equal 'hello everyone' at Context. (test\util.test.js:10:27) at processImmediate (internal/timers.js:456:21)
- expected - actual
-"hello world" +"hello everyone"
If you still want it: change the implementation at Util.js to something like this.
Proof:
Note: it is still not dependency injection but little change on how func2 get called.