【问题标题】:How to stub ES6 node_modules when using import?使用导入时如何存根 ES6 node_modules?
【发布时间】:2018-02-18 02:57:24
【问题描述】:

我在编写测试时有点困惑。我的堆栈是 mocha、chai 和 sinon + babel 来编译。最近我开始使用 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,但我没有设法让它工作。尝试使用 import * as uuid from 'uuid' 导入所有 uuid。但在我的 service.js 中,它仍然是 被调用的原始函数...... 另外,由于导入应该是只读的,一旦它是本机的,这个解决方案就行不通了......

我在网上找到的唯一有趣的事情是这个解决方案,在我的服务中添加一个函数,以便让外界覆盖我的依赖项。 (见https://railsware.com/blog/2017/01/10/mocking-es6-module-import-without-dependency-injection/)。

import * as originalUuid from 'uuid';

let {v4} = originalUuid;
export function mock(mockUuid) {
  ({v4} = mockUuid || originalUuid);
}

编写这个小样板代码是可以的,但是将它添加到我的代码中很麻烦...我更愿意在我的测试或一些配置中编写样板代码。另外,我不想 有一个 IoC 容器,我想尽可能少地保留我的功能并尽可能保持功能......

你有什么想法吗? :)

【问题讨论】:

  • 如果将 ES6 模块转译为 CommonJS 和 require,则可以使用缓存处理库 - proxyquire、rewire 等。

标签: javascript unit-testing import ecmascript-6 stub


【解决方案1】:

您应该可以为此使用proxyquire 之类的模块。这不是经过测试的代码,但会如下所示:

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

【讨论】:

  • 即使使用导入语法(转译)也能完美运行。也许有一天,我们需要另一种解决方案,但就目前而言,它是完美的。非常感谢。
猜你喜欢
  • 2019-04-06
  • 1970-01-01
  • 2017-01-20
  • 2023-04-08
  • 2019-10-22
  • 2020-06-28
  • 2016-04-07
  • 1970-01-01
  • 2016-10-25
相关资源
最近更新 更多