如何在ES6中存根导出功能? [英] How to stub exported function in ES6?

查看:99
本文介绍了如何在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');
  });
});

这篇关于如何在ES6中存根导出功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆