Supertest路线与模拟服务
问题描述:
UPDATESupertest路线与模拟服务
我更新了下面的代码,以反映我的解决方案。弄清楚它是相当混乱的,但希望它能帮助别人。
我想弄清楚如何测试我的路线。我遇到的问题是,当我使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();
});
});
})
答
我想这样做是改变你的方法,唯一的方法:
exports.placesDetails = function (req, res, places)
创建额外的方法:
exports.placesDetailsForGoogle = function (req, res) {
exports.placesDetails(req, res, new GooglePlaces('MY_KEY'));
}
,并写一个测试执行placesDetails,通过适当的嘲笑 '地方' 对象。您将测试placesDetails逻辑与此同时您将有实际的代码中使用的舒适的功能,而无需每次实例化实例化GooglePlaces对象。