我还在学习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();
});
});
});我有点困惑。非常感谢。
发布于 2017-11-22 22:38:36
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 });
});我真的希望有更好的方法来做你想做的事情。我相信类的构造函数也有类似的行为,这让我认为其他类也有类似的问题(参见下面的问题)。您可能应该加入该repo上的对话或其他讨论,如果半年后这仍然是您的一个活动项目,但没有任何回应,那么您应该在这里为其他人发布答案。
https://stackoverflow.com/questions/42749400
复制相似问题