存根内部function?
我想在unit testing时在我的代码中存储一个内部函数,例如:
//foobar.js const uuid = require('uuid'); function foo() { console.log('uuid: ' + uuid.v4()); // Lots of timers } exports._foo = foo; function bar() { //Logic... foo(); //Logic... } exports.bar = bar;
而unit testing:
// test/foobar.js const chai = require('chai'), expect = chai.expect, proxyquire = require('proxyquire'), sinon = require('sinon'); describe('bar', () => { it('call foo', () => { let foo = proxyquire('./foo.js', { uuid: { v4: () => { return '123456789'; } } }), fooSpy = sinon.spy(foo._foo); foo.bar(); expect(fooSpy.calledOnce); }); });
现在unit testingbar
,我可以监视foo
就好了,这样挺好的。
然而,真正的foo
会耗费大量的时间(DB调用,文件IO …),而且我可以使用proxyquire来存储所有的fs
和db调用立即终止,这将复制来自foo
testing的代码,难以理解,而且完全不好。
简单的解决scheme是存根foo
,但是proxyquire似乎并不喜欢那样。 一个天真的foo._foo = stubFoo
也没有工作。 Rewire似乎也没有处理这个。
我能做的就是创build一个文件,导入和导出foobar.js,并使用它的代理,但这个想法本身已经不好了。
testingbar
时如何存储foo
函数?