How to mock an inner function in Sinon?

Viewed 7420

Suppose I have two functions, foo is called inside a bar. I have a Meteor app, so I decided to use meteor mocha package along with sinon and chai and not jest

// foo.js

const foo = () => // call to a google maps api;
export default foo;


// bar.js

const bar = (x) => {
  foo();
  ...
};
export default bar;

What is the correct approach of mocking foo in this case

Currently I've came up with the following solution:

import foo from 'path/to/foo.js'
import bar from 'path/to/bar.js'

describe('my test suite', function() {
  it('should pass the test', function() {
    foo = spy();
    bar(5);
    assert(foo.calledOnce);
  });
}); 

The following code works, but is that correct to redefine foo?

UPDATE

Also, it's not possible to create a mock or stub this way, which makes me think that Sinon is not suitable for mocking standalone functions

1 Answers

Sinon works well on standalone JavaScript functions.

Here is an example of how to wrap the default export of a module in a Sinon spy:

import * as sinon from 'sinon';
import * as fooModule from 'path/to/foo.js'
import bar from 'path/to/bar.js'

describe('my test suite', function() {
  it('should pass the test', function() {
    const spy = sinon.spy(fooModule, 'default');  // wrap the function in a spy
    bar(5);
    assert(spy.calledOnce);  // SUCCESS
    spy.restore();  // restore the original function
  });
}); 

Here is an example of how to replace the default export of a module with a Sinon stub:

import * as sinon from 'sinon';
import * as fooModule from 'path/to/foo.js'
import bar from 'path/to/bar.js'

describe('my test suite', function() {
  it('should pass the test', function() {
    const stub = sinon.stub(fooModule, 'default').returns('something else');  // stub the function
    bar(5);  // foo() returns 'something else' within bar(5)
    assert(stub.calledOnce);  // SUCCESS
    stub.restore();  // restore the original function
  });
});
Related