【发布时间】: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