dimanche 25 janvier 2015

Using sinon and mocha to test node.js http.get

Let's say I have the following function



'use strict';
var http = require('http');

var getLikes = function(graphId, callback) {
// request to get the # of likes
var req = http.get('http://ift.tt/rrPc6B' + graphId, function(response) {
var str = '';
// while data is incoming, concatenate it
response.on('data', function (chunk) {
str += chunk;
});
// data is fully recieved, and now parsable
response.on('end', function () {
var likes = JSON.parse(str).likes;
var data = {
_id: 'likes',
value: likes
};
callback(null, data);
});
}).on('error', function(err) {
callback(err, null);
});
};

module.exports = getLikes;


I would like to test it with mocha AND sinon, but I don't get how to stub the http.get.


For now I'm doing a real http.get to facebook, but I would like to avoid it.


Here is my current test:



'use strict';
/*jshint expr: true*/
var should = require('chai').should(),
getLikes = require('getLikes');

describe('getLikes', function() {

it('shoud return likes', function(done) {
getLikes(function(err, likes) {
should.not.exist(err);
likes._id.should.equal('likes');
likes.value.should.exist();
done();
});
});

});


How can I achieve what I want, without relying on something else than sinon? (I don't want to use the request module to perform the get, or using another testing lib)


Thanks!


Aucun commentaire:

Enregistrer un commentaire