带有proxyquire和sinon的google-geocoder

我还是很学习node,js,sinon,proxyquire等

我有一个使用谷歌地理编码模块( https://github.com/bigmountainideas/google-geocoder )的模块,我正在努力编写一个testing来存根。

这一切都归结为我想你如何设置它。 在time.js中,我按照google-geocoder文档进行如下操作:

var geocoder = require('google-geocoder'); ... module.exports = function(args, callback) { var geo = geocoder({ key: some-thing }); geo.find('new york', function(err, response) { ... }); } 

我想要testing如下,但我得到的错误:

  TypeError: geo.find is not a function at run (cmdsUser/time.js:x:x) at Context.<anonymous> (tests/cmdsUser/time-test.js:x:x) 

时间test.js:

 var time; var findStub; before(function () { findStub = sinon.stub() time = proxyquire('./../../cmdsUser/time',{ 'google-geocoder': { find: findStub } } ); }); describe('Demo test', function() { it('Test 1', function(done){ findStub.withArgs('gobbledegook').yields(null, { this-is: { an-example: 'invalid' } }); time(['gobbledegook'], function(err, response) { expect(response).to.equals('No result for gobbledegook'); done(); }); }); }); 

我有点困惑。 非常感谢。

google-geocode的出口似乎被格式化为:

 { function() { [...] // Will return an instance of GeoCoder } GeoCoder: { [...] __proto__: { find: function() { // Replace me! } } }, GeoPlace: [...] } 

proxyquire似乎replace返回实例的函数,即使在使用键"GeoCoder" find对象的情况下,通过将方法find实际分配给正确的对象,使您更接近解决scheme。 我做了一个testing项目,试图学习克服这个最好的方法,我觉得有点卡住了。 但是既然你以前是callThru ,那么你不妨做一些proxyquire的肮脏的工作,然后传递依赖的残存版本。

 before(function() { // Stub, as you were before findStub = sinon.stub() // Require the module yourself to stub stubbedDep = require('google-geocoder') // Override the method with the extact code used in the source stubbedDep.GeoCoder.prototype.find = findStub // Pass the stubbed version into proxyquire test = proxyquire('./test.js', { 'google-geocoder': stubbedDep }); }); 

我真的希望有更好的方法来做你想做的事情。 我相信阶级的build构者也是以类似的方式行事,这让我觉得其他人也有类似的问题(见下面的问题)。 你可能应该join那个对话或其他的回购,并在这里为其他人回答这个问题,如果这个问题在你半年之后仍然是一个积极的项目而没有回应的话。

问题: #136 , #144 , #178