3

UPDATE

I updated the code below to reflect my solution. It was rather confusing to figure it out but hopefully it will help someone else too.

I'm trying to figure out how to test my routes. The issue I'm running into is, when I make the GET request my node-googleplaces service calls out to the google api. Is there a way to mock out this service so that I can test my route and just fake the data it returns?

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

})

1 Answer 1

0

The only way I'm thinking about to do it is to change your method to:

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

create additional method:

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

and write a test that executes placesDetails, passing properly mocked 'places' object. You'll test placesDetails logic with this and at the same time you'll have comfy function to be used in actual code without need to actualy instantiate GooglePlaces object every time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.