我正在使用Mocha和Sinon编写单元测试,并且我想模拟一个使用ES6样式import
的依赖项。下面,我提供了我正在尝试做的简化版本以及我尝试过的方法。
当我在线研究时,最初我读到Sinon无法模拟ES6模块。但是,在其他地方,我读到它可以通过使用import * as syntax
来实现。我找到了一些尝试使用的示例。但是,到目前为止,它们还没有起作用。
我还查看了其他库的文档,例如proxyquire和rewire。但是,它们似乎是围绕Node样式require
而不是ES6样式import
来定位的。
有没有一种普遍接受的方法来处理使用import
的模拟依赖项?
我尝试过的内容的简化版本:
dependency.js
export function foo {
return {
bar: () => console.log('In real bar')
};
};
unitUnderTest.js
import { foo } from './dependency.js';
export const exportedFunction = () => foo.bar();
testFile.js
import sinon from 'sinon';
import * as dependency from './dependency.js';
import { exportedFunction } from './unitUnderTest';
describe(`Things that I've tried`, () => {
it('Stub dependency', () => {
let stub;
before(() => {
stub = sinon.stub(dependency)
.returns({
foo: () => ({
bar: () => console.log('In mocked bar')
})
});
});
exportedFunction();
});
it('Stub dependency.foo', () => {
let stub;
before(() => {
stub = sinon.stub(dependency, 'foo')
.returns({
bar: () => console.log('In mocked bar')
});
});
exportedFunction();
});
it('Stub dependency.foo directly', () => {
let stub;
before(() => {
stub = sinon.stub(dependency.foo)
.returns({
bar: () => console.log('In mocked bar')
});
});
exportedFunction();
});
describe(`Things that I've tried using default`, () => {
it('Stub dependency.default', () => {
let stub;
before(() => {
stub = sinon.stub(dependency, 'default')
.returns({
foo: () => {
bar: () => console.log('In mocked bar')
}
})
});
exportedFunction();
});
it('Stub dependency.default.foo', () => {
let stub;
before(() => {
stub = sinon.stub(dependency.default.foo, 'bar', () => console.log('In mocked bar'));
});
exportedFunction();
});
it('Mock dependency.default.foo', () => {
let stub;
before(() => {
stub = sinon.mock(depencency.default.foo)
.expects('bar')
.once();
})
exportedFunction();
dependency.foo.bar.verify(); // Throws an error, cannon call verify of undefined
});
});
});