2015-06-26 43 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'); 
//... 

希望它能幫助!

相關問題