jeudi 25 juin 2015

Why rewire not inject mock for testing in nodejs?

I'm trying to inject a mock for testing using mocha. But it looks like the mock is not picked up and the test still uses the real data from server. I'm trying to get the data from foursquare.

Here's my code.

var foursquare = require('foursquarevenues'),
    Promise = require('promise'),
    _ = require('underscore');

var Foursquare = function(client_id, client_secret) {
    this.the_4sqr_lib = foursquare(client_id, client_secret);

};
Foursquare.prototype.getVenue = function(id) {
    var self = this;
    return new Promise(function(resolve, reject) {
        self.the_4sqr_lib.getVenue({'venue_id' : id}, function(error, response) {
            if(error) {
                reject(error);
            }
            var venueData = response.response.venue;
            var firstPhoto =  venueData.photos.groups[0].items[0];
            var theVenue = {
                id: venueData.id,
                name: venueData.name,
                photo: firstPhoto.prefix + firstPhoto.width + 'x' + firstPhoto.height + firstPhoto.suffix,
                url: venueData.canonicalUrl
            };
            resolve(theVenue);  
        });
    });
    };

module.exports = Foursquare;

And here's my test

var rewire = require("rewire"),
    Foursquare = rewire('../../lib/foursquare.js');

        var client_id, client_secret, foursquare;
        beforeEach(function() {
            client_id = process.env.FOURSQUARE_CLIENT_ID;
            client_secret = process.env.FOURSQUARE_CLIENT_SECRET;
            foursquare = new Foursquare(client_id, client_secret);
        });
        it('should get venue without photo', function(done) {
            var mockFoursquare = {
                getVenue : function(id, cb) {
                    var response = {
                        response : {
                            response : {
                                venue : {
                                    photos : {
                                        count:0,
                                        groups : []
                                    }
                                }
                            }
                        }
                    }
                    cb(null, response);
                }
            };

            Foursquare.__set__('foursquarevenues', mockFoursquare);

            var venue = foursquare.getVenue('430d0a00f964a5203e271fe3');
            venue.then(function(venue) {
            venue.id.should.equal('');
            venue.name.should.equal('');
            venue.photo.should.equal('');
            venue.url.should.equal('');
            done();
            }).catch(done);
        });

I'm expecting the test to fail because of undefined but it's still getting the real data.

Aucun commentaire:

Enregistrer un commentaire