更新
我更新了以下代码以反映我的解决方案。想弄清楚它是相当混乱的,但希望它也能帮助其他人。
我试图弄清楚如何测试我的路线。我遇到的问题是,当我发出GET
请求时,node-googleplaces
服务会调用google api。有没有办法模拟这个服务,以便我可以测试我的路线,只是伪造它返回的数据?
controller.js
'use strict';
var path = require('path'),
GooglePlaces = require('node-googleplaces');
exports.placesDetails = function (req, res) {
var places = new GooglePlaces('MY_KEY');
var params = {
placeid: req.params.placeId,
};
//this method call will be replaced by the test stub
places.details(params, function (err, response) {
var updatedResponse = 'updated body here'
res.send(updatedResponse)
});
};
test.js
var should = require('should'),
//seem weird but include it. The new version we're making will get injected into the app
GooglePlaces = require('node-googleplaces');
request = require('supertest'),
path = require('path'),
sinon = require('sinon'),
describe(function () {
before(function (done) {
//create your stub here before the "app" gets instantiated. This will ensure that our stubbed version of the library will get used in the controller rather than the "live" version
var createStub = sinon.stub(GooglePlaces, 'details');
//this will call our places.details callback with the 2nd parameter filled in with 'hello world'.
createStub.yields(null, 'hello world');
app = express.init(mongoose);
agent = request.agent(app);
done();
});
it('should get the data', function (done) {
agent.get('/api/gapi/places/search/elmersbbq')
.end(function (err, res) {
if (err) {
return done(err);
}
console.log(res.body)
done();
});
});
})
答案 0 :(得分:0)
我正在考虑的唯一方法是将您的方法更改为:
exports.placesDetails = function (req, res, places)
创建其他方法:
exports.placesDetailsForGoogle = function (req, res) {
exports.placesDetails(req, res, new GooglePlaces('MY_KEY'));
}
并编写一个执行 placesDetails 的测试,并正确传递模拟的' places '对象。您将使用此方法测试 placesDetails 逻辑,同时您将在实际代码中使用舒适的函数,而无需每次都实例化GooglePlaces对象。