gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:27:57 24 4
gpt4 key购买 nike

我还在学习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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com