Mike Chaliy Mike Chaliy - 1 month ago 15
Javascript Question

How to stub exported function in ES6?

I have file foo.js:

export function bar (m) {
console.log(m);
}


And another file that uses foo.js, cap.js:

import { bar } from 'foo';

export default m => {
// Some logic that I need to test
bar(m);
}


I have test.js:

import cap from 'cap'

describe('cap', () => {
it('should bar', () => {
cap('some');
});
});


Somehow I need override implementation of
bar(m)
in test. Is there any way to do this?

P.S. I use babel, webpack and mocha.

Answer

Ouch.. I found solution, so I use sinon to stub and import * as foo from 'foo' to get object with all exported functions so I can stub them.

import sinon from 'sinon';
import cap from 'cap';
import * as foo from 'foo';

sinon.stub(foo, 'bar', m => {
    console.log('confirm', m);
});

describe('cap', () => {
  it('should bar', () => {
    cap('some');
  });
});