Node.js 谷歌地理编码器与proxyquire和sinon

Node.js 谷歌地理编码器与proxyquire和sinon,node.js,unit-testing,sinon,proxyquire,Node.js,Unit Testing,Sinon,Proxyquire,我仍然在学习node、js、sinon、proxyquire等 我有一个使用GoogleGeocode模块()的模块,我正在努力编写一个测试来存根它 我想这一切都归结于你是如何设置的。在time.js中,我根据google geocoder文档执行以下操作: var geocoder = require('google-geocoder'); ... module.exports = function(args, callback) { var geo = geocoder({ ke

我仍然在学习node、js、sinon、proxyquire等

我有一个使用GoogleGeocode模块()的模块,我正在努力编写一个测试来存根它

我想这一切都归结于你是如何设置的。在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) { ... });
}
我试图进行如下测试,但我得到了错误:

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

我有点困惑。非常感谢。

谷歌地理编码
的导出文件格式如下:

{
    function() {
        [...]
        // Will return an instance of GeoCoder
    }
    GeoCoder: {
        [...]
        __proto__: {
            find: function() {
                // Replace me!
            }
        }
    },
    GeoPlace: [...]
}
proxyquire
似乎取代了返回实例的函数,即使在对象中使用键
“GeoCoder”
包装
find
时也是如此,它通过实际将方法
find
分配给正确的对象,使您更接近解决方案。我做了一个测试项目,试图学习克服这个问题的最佳方法,我觉得有点卡住了。但是,由于您以前是
调用thru
,因此您最好先执行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 });
});
我真的希望有更好的方法来做你想做的事。我相信类的构造函数以类似的方式工作,这让我觉得其他人也有类似的问题(见下面的问题)。如果半年后这仍然是你的一个活跃项目,没有任何回应,你可能应该加入这个对话或其他关于回购协议的对话,并在这里为其他人发布一个答案

问题:

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 });
});