httprequest - Testing an http request error using sinon -


i'm using stubs write tests http request function such

// api.js var https = require('https');  function httpsget(domain, options, parameters)        var deferred = q.defer();    var request = https.request(options, function(res) {     var resbody = '';     res.on('data', function(data) {       resbody += data;     });     res.on('end', function() {       if (resbody.length > 0) {         try {           var response = json.parse(resbody);           if(response.error) {             var errorstring = domain;             for(var key in parameters){               errorstring += '\n\t' + key + ' - ' + parameters[key];                 }             deferred.reject(new error(errorstring + '\n' + response.error.code + ' - ' + response.error.message + ' - ' + response.error.reference));           }           deferred.resolve(response);         }         catch(err) {           deferred.reject(new error('error: response not json ' + domain));           }         }         else {           deferred.reject(new error('response body of ' + domain + ' https call empty.'));         }       });     });     request.on('error', function(error) {       deferred.reject(new error('error: ' + error));     });     request.end();   }   return deferred.promise; }  module.exports = {     httpsget: httpsget }; 

how able test request.on('error', function() {}) statement? i'm trying using mocha, stubs , streams , don't feel i'm understanding @ all. can't seem create erroneous request leads statement.

try this:

var assert = require('assert');  describe('httpsget functional tests', function () {     it('should catch error', function (done) {         httpsget('', {})             // don't want resolve.             .then(function () {                 done('expected invocation reject');             })             // expect rejection.             .catch(function (err) {                 // console.log(err);                 assert(/econnrefused/.test(err.message), 'should error');                 done();             })             // in case still have error.             .catch(done);     }); }); 

all need trigger old error in http request.

to honest though, i'd swap using request because handles of low level stuff you. can use nock provide fake responses test.