【问题标题】:google-geocoder with proxyquire and sinon带有 proxyquire 和 sinon 的 google-geocoder
【发布时间】:2017-08-02 15:05:48
【问题描述】:

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

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

这一切都归结为我认为你是如何设置它的。在 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)

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

我有点困惑。非常感谢。

【问题讨论】:

    标签: node.js unit-testing sinon proxyquire


    【解决方案1】:

    google-geocode 的导出格式似乎为:

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

    proxyquire 似乎替换了返回实例的函数,即使在使用键 "GeoCoder"find 包装在对象中时,通过实际将方法 find 分配给正确的对象,这使您更接近解决方案。我做了一个测试项目来尝试学习克服这个问题的最佳方法,但我觉得有点卡住了。但是既然你之前是callThru'ing,你还不如做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 });
    });
    

    我真的希望有更好的方法来做你想做的事。我相信类的构造函数以类似的方式行事,这让我认为其他人也有类似的问题(见下面的问题)。如果半年多后这仍然是您的活跃项目而没有任何回应,您可能应该加入该回购上的该对话或其他对话,并在此处为其他人发布答案。

    问题:#136#144#178

    【讨论】:

      猜你喜欢
      • 2018-08-12
      • 2014-08-03
      • 1970-01-01
      • 2015-07-10
      • 2020-10-24
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多