Mik*_*liy 52 javascript ecmascript-6
我有文件foo.js:
export function bar (m) {
console.log(m);
}
Run Code Online (Sandbox Code Playgroud)
另一个使用foo.js,cap.js的文件:
import { bar } from 'foo';
export default m => {
// Some logic that I need to test
bar(m);
}
Run Code Online (Sandbox Code Playgroud)
我有test.js:
import cap from 'cap'
describe('cap', () => {
it('should bar', () => {
cap('some');
});
});
Run Code Online (Sandbox Code Playgroud)
不知怎的,我需要覆盖bar(m)
测试中的实现.有没有办法做到这一点?
PS我使用babel,webpack和mocha.
Mik*_*liy 60
哎哟..我找到了解决方案,所以我用sinon
stub import * as foo from 'foo'
来获取所有导出函数的对象,所以我可以将它们存根.
import sinon from 'sinon';
import cap from 'cap';
import * as foo from 'foo';
sinon.stub(foo, 'bar', m => {
console.log('confirm', m);
});
describe('cap', () => {
it('should bar', () => {
cap('some');
});
});
Run Code Online (Sandbox Code Playgroud)
您只能从模块本身中替换/重写/存根导出.(这是一个解释)
如果你像这样重写'foo.js':
var bar = function bar (m) {
console.log(m);
};
export {bar}
export function stub($stub) {
bar = $stub;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在测试中覆盖它,如下所示:
import cap from 'cap'
import {stub} from 'foo'
describe('cap', () => {
it('should bar', () => {
stub(() => console.log('stubbed'));
cap('some'); // will output 'stubbed' in the console instead of 'some'
});
});
Run Code Online (Sandbox Code Playgroud)
我创建了一个Babel插件,可以自动转换所有导出,以便它们可以存根:https://github.com/asapach/babel-plugin-rewire-exports
@Mike解决方案可以在旧版本的sinon中使用,但自sinon 3.0.0起已将其删除。
现在代替:
sinon.stub(obj, "meth", fn);
Run Code Online (Sandbox Code Playgroud)
你应该做:
stub(obj, 'meth').callsFake(fn)
Run Code Online (Sandbox Code Playgroud)
模拟Google oauth api的示例:
import google from 'googleapis';
const oauth2Stub = sinon.stub();
sinon.stub(google, 'oauth2').callsFake(oauth2Stub);
oauth2Stub.withArgs('v2').returns({
tokeninfo: (accessToken, params, callback) => {
callback(null, { email: 'poo@bar.com' }); // callback with expected result
}
});
Run Code Online (Sandbox Code Playgroud)