我试图使用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
而失败,但它仍然可以获得真实数据。
答案 0 :(得分:0)
使用var self = this;
时遇到了同样的问题。像self.someMethod()
这样的方法并没有被嘲笑。
我通过分配没有重新连接的模拟部分解决了它:
MyModule = rewire('../lib/MyModule');
MyModule.__set__({"someMethodNotUsingSelf": function(){...}});
MyModule.someMethodThatUsesSelf = function() { //some mock code };
someValue.should.equal('something');
//...
希望它有所帮助!