gpt4 book ai didi

javascript - 使用导入时如何 stub ES6 node_modules?

转载 作者:行者123 更新时间:2023-11-29 21:01:42 25 4
gpt4 key购买 nike

我在写测试的时候有点困惑。我的堆栈是 mocha、chai 和 sinon + babel 来转译。最近我开始使用 ES6 导入和导出。到目前为止它运行良好,但我在模拟某些依赖项时遇到了麻烦。这是我的案例:

服务.js

import {v4} from 'uuid';

function doSomethingWithUuid() {
return v4();
}

export function doSomething() {
const newUuid = doSomethingWithUuid();
return newUuid;
}

服务.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 容器,我想尽可能少地保留我的功能并尽可能保持功能......

你有什么想法吗? :)

最佳答案

您应该能够使用类似 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.
});
});

关于javascript - 使用导入时如何 stub ES6 node_modules?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46129066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com