node.js - 带有 proxyquire 和 sinon 的 google-geocoder

标签 node.js unit-testing sinon proxyquire

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

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

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

时间测试.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 似乎取代了返回实例的函数,即使在使用键 "GeoCoder"find 包装在对象中时也是如此通过实际将方法 find 分配给正确的对象,更接近解决方案。我做了一个测试项目来尝试学习克服这个问题的最佳方法,但我感觉有点卡住了。但由于您之前是 callThru'ing,因此您不妨做 proxyquire 的肮脏工作,然后传递依赖项的 stub 版本。

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

关于node.js - 带有 proxyquire 和 sinon 的 google-geocoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42749400/

相关文章:

node.js - 如何通过nextjs在websocket中集成ssl?

java - Nodejs 加密 ECDH 公钥十六进制为 X.509

node.js - 填充 Mongoose 的条件

node.js - 尝试对 Node 模块内使用的方法进行 stub

javascript - 如果异步调用,如何在测试函数B内部测试函数A是否被调用

reactjs - React 测试 - TypeError : localStorage. getItem 不是函数

node.js - Node.js 中的 util.error 和 console.error 有什么区别?

Android Test Monkey - 设置详细程度?

python - 无法让 pytest 理解设置中的命令行参数

python - 带有补丁的单元测试行为(Flask)