Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinon not working for exported function

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?

like image 719
Hommer Smith Avatar asked Aug 10 '26 05:08

Hommer Smith


1 Answers

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.

like image 85
Yu Huang Avatar answered Aug 12 '26 17:08

Yu Huang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!