gpt4 book ai didi

node.js - 具有模拟服务的 super 测试路线

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

更新

我更新了下面的代码以反射(reflect)我的解决方案。弄清楚它相当令人困惑,但希望它对其他人也有帮助。

我正在尝试找出如何测试我的路线。我遇到的问题是,当我发出 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的测试,传递正确模拟的“places”对象。您将用它来测试 placesDetails 逻辑,同时您将拥有在实际代码中使用的舒适函数,而无需每次都实际实例化 GooglePlaces 对象。

关于node.js - 具有模拟服务的 super 测试路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35735401/

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