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
測試失敗,但它仍然得到真實數據。
如果你在'新Foursquare(client_id,client_secret)'之前做模擬會怎麼樣? –
結果仍然相同。 – toy