2016-03-01 53 views
2

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(); 
       }); 
    }); 

}) 

回答

0

我想這樣做是改變你的方法,唯一的方法:

exports.placesDetails = function (req, res, places) 

創建額外的方法:

exports.placesDetailsForGoogle = function (req, res) { 
    exports.placesDetails(req, res, new GooglePlaces('MY_KEY')); 
} 

,並寫一個測試執行placesDetails,通過適當的嘲笑 '地方' 對象。您將測試placesDetails邏輯與此同時您將有實際的代碼中使用的舒適的功能,而無需每次實例化實例化GooglePlaces對象。