I have a really simple JS lib (called trysinon.js) that looks like this:
export function foo() {
bar();
}
export function bar() {
return 2;
}
And I have the following test
import expect from 'expect';
import sinon from 'sinon';
import * as trysinon from 'trysinon';
describe('trying sinon', function() {
beforeEach(function() {
sinon.stub(trysinon, 'bar');
});
afterEach(function() {
trysinon.bar.restore();
});
it('calls bar', function() {
trysinon.foo();
expect(trysinon.bar.called).toBe(true);
});
});
And the test is failing. How can I ensure the test passes?
Because in foo()
, you called bar()
which is inner function of trysinon.js. This bar()
is different with the bar()
you stubbed which is exported. The best way is to change trysinon
to class, or called exported bar()
in foo()
as following.
function bar() { return 2; }
module.exports.bar = bar;
function foo() {
module.exports.bar();
}
module.exports.foo = foo;
then you can stub bar()
with sinon.stub(trysinon, 'bar').returns(2)
Hope this can help you.