如何在ES6中存根导出功能?

如何在ES6中存根导出功能?

问题描述:

我有文件foo.js:

I have file foo.js:

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

另一个使用foo.js的文件,cap.js:

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);
}

我有test.js:

import cap from 'cap'

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

不知何故,我需要覆盖 bar(m)在测试。有没有办法这样做?

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

我使用babel,webpack和mocha。

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

Ouch ..我找到解决方案,所以我使用 sinon to stub和 import *作为foo从'foo'获取所有导出函数的对象,所以我可以存根。

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');
  });
});