![](/img/trans.png)
[英]nodejs testing with rewire and mocha SyntaxError: Unexpected token
[英]Why rewire not inject mock for testing in nodejs?
我正在嘗試注入模擬以使用Mocha進行測試。 但是看起來模擬沒有被拾取,並且測試仍然使用來自服務器的真實數據。 我正在嘗試從foursquare獲取數據。
這是我的代碼。
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
而失敗,但是它仍在獲取真實數據。
使用var self = this;
時,我遇到了同樣的問題var self = this;
。 像self.someMethod()
這樣的方法沒有被嘲笑。
我已經通過分配模擬而不重新布線而部分解決了它:
MyModule = rewire('../lib/MyModule');
MyModule.__set__({"someMethodNotUsingSelf": function(){...}});
MyModule.someMethodThatUsesSelf = function() { //some mock code };
someValue.should.equal('something');
//...
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.