Javascript 使用导入时如何存根ES6节点_模块?

Javascript 使用导入时如何存根ES6节点_模块?,javascript,unit-testing,import,ecmascript-6,stub,Javascript,Unit Testing,Import,Ecmascript 6,Stub,我在写测试的时候有点困惑。我的堆栈是摩卡、柴和西农+巴贝尔传输。最近我开始使用ES6导入和导出。到目前为止,它工作得很好,但是我在模拟一些依赖项时遇到了麻烦。我的情况如下: service.js import {v4} from 'uuid'; function doSomethingWithUuid() { return v4(); } export function doSomething() { const newUuid = doSomethingWithUuid()

我在写测试的时候有点困惑。我的堆栈是摩卡、柴和西农+巴贝尔传输。最近我开始使用ES6导入和导出。到目前为止,它工作得很好,但是我在模拟一些依赖项时遇到了麻烦。我的情况如下:

service.js

import {v4} from 'uuid';

function doSomethingWithUuid() {
    return v4();
}

export function doSomething() {
    const newUuid = doSomethingWithUuid();
    return newUuid;
}
service.test.js

import {doSomething} from './service';

describe('service', () => {
    it('should doSomething' () => {
        // how to test the return of doSomething ? 
        // I need to stub v4 but I don't know how...
    });
});
我考虑过的事情:sinon.stub,但我还没有设法让它起作用。正在尝试从“uuid”导入所有uuid,并将其作为uuid导入
import*
。但在我的service.js中,它仍然是 原始函数名为。。。 另外,由于导入应该是只读的,一旦它是本机的,这个解决方案就不起作用了

我在网上发现的唯一有趣的事情就是这个解决方案,在我的服务中添加一个函数,以便让外部世界覆盖我的依赖关系。 (见附件)

这是可以写这个小样板代码,但它困扰我添加到我的代码。。。我更喜欢在我的测试或一些配置中编写样板文件。另外,我不想 有一个IoC容器,我希望尽可能少地保留我的函数,并尽可能保持功能性


你有什么想法吗?:)

您应该能够使用这样的模块来完成此任务。这是未经测试的代码,但它将如下所示:

const proxyquire = require('proxyquire');
const uuidStub = { };

const service = proxyquire('./service', { uuid: uuidStub });
uuidStub.v4 = () => 'a4ead786-95a2-11e7-843f-28cfe94b0175';

describe('service', () => {
  it('should doSomething' () => {
    // doSomething() should now return the hard-coded UUID
    // for predictable testing.
  });
});

如果ES6模块被传输到CommonJS和
require
,则可以利用缓存损坏库-proxyquire、rewire等。即使使用导入语法(传输),它也可以完美地工作。也许有一天,我们需要另一个解决方案,但现在,它是完美的。谢谢。
const proxyquire = require('proxyquire');
const uuidStub = { };

const service = proxyquire('./service', { uuid: uuidStub });
uuidStub.v4 = () => 'a4ead786-95a2-11e7-843f-28cfe94b0175';

describe('service', () => {
  it('should doSomething' () => {
    // doSomething() should now return the hard-coded UUID
    // for predictable testing.
  });
});