首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用proxyquire和sinon的google-geocoder

使用proxyquire和sinon的google-geocoder
EN

Stack Overflow用户
提问于 2017-03-12 23:40:57
回答 1查看 76关注 0票数 2

我还在学习node,js,sinon,proxyquire等。

我有一个使用google-geocode模块(https://github.com/bigmountainideas/google-geocoder)的模块,我正在努力编写一个测试来存根它。

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

代码语言:javascript
复制
var geocoder = require('google-geocoder');

  ...

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

我尝试按如下方式进行测试,但得到了错误:

代码语言:javascript
复制
  TypeError: geo.find is not a function
   at run (cmdsUser/time.js:x:x)
   at Context.<anonymous> (tests/cmdsUser/time-test.js:x:x)

time-test.js:

代码语言:javascript
复制
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();
    });
  });
});

我有点困惑。非常感谢。

EN

回答 1

Stack Overflow用户

发布于 2017-11-22 22:38:36

google-geocode的导出格式似乎是这样的:

代码语言:javascript
复制
{
    function() {
        [...]
        // Will return an instance of GeoCoder
    }
    GeoCoder: {
        [...]
        __proto__: {
            find: function() {
                // Replace me!
            }
        }
    },
    GeoPlace: [...]
}

proxyquire似乎替换了返回实例的函数,即使在使用键"GeoCoder"find包装在对象中时也是如此,这通过将方法find实际分配给正确的对象,使您更接近解决方案。我做了一个测试项目,试图学习克服这个问题的最好方法,但我感觉有点卡住了。但是既然你之前是callThru'ing,你还不如做proxyquire的脏活,然后传递依赖项的存根版本。

代码语言:javascript
复制
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 });
});

我真的希望有更好的方法来做你想做的事情。我相信类的构造函数也有类似的行为,这让我认为其他类也有类似的问题(参见下面的问题)。您可能应该加入该repo上的对话或其他讨论,如果半年后这仍然是您的一个活动项目,但没有任何回应,那么您应该在这里为其他人发布答案。

问题:#136#144#178

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42749400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档