2015-06-26 37 views
0

我正在尝试使用摩卡注入一个模拟测试。但它看起来像模拟没有拿起,测试仍然使用服务器的真实数据。我试图从四方得到数据。为什么rewire不能在nodejs中注入模拟测试?

这是我的代码。

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; 

这是我的测试

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

我很期待,因为undefined测试失败,但它仍然得到真实数据。

+0

如果你在'新Foursquare(client_id,client_secret)'之前做模拟会怎么样? –

+0

结果仍然相同。 – toy

回答

0

我在使用var self = this;时遇到同样的问题。像self.someMethod()这样的方法并没有被嘲笑。

我已经部分地被无联控分配模拟解决它:

MyModule = rewire('../lib/MyModule'); 
MyModule.__set__({"someMethodNotUsingSelf": function(){...}}); 
MyModule.someMethodThatUsesSelf = function() { //some mock code }; 
someValue.should.equal('something'); 
//... 

希望它能帮助!

相关问题