使用sinon测试http请求错误

时间:2016-06-06 22:45:52

标签: httprequest mocha sinon

我目前正在使用存根来编写http请求函数的测试

// 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 from ' + domain));
          }
        }
        else {
          deferred.reject(new Error('Response body of ' + domain + ' HTTPs call is empty.'));
        }
      });
    });
    request.on('error', function(error) {
      deferred.reject(new Error('Error: ' + error));
    });
    request.end();
  }
  return deferred.promise;
}

module.exports = {
    httpsGet: httpsGet
};

我如何测试request.on('error',function(){})语句?我正在尝试使用摩卡,存根和流,我觉得我根本不理解这一点。我似乎无法创建导致该陈述的错误请求。

1 个答案:

答案 0 :(得分:0)

试试这个:

var assert = require('assert');

describe('httpsGet functional tests', function () {
    it('should catch an error', function (done) {
        httpsGet('', {})
            // We don't want it to resolve.
            .then(function () {
                done('Expected invocation to reject');
            })
            // We do expect a rejection.
            .catch(function (err) {
                // console.log(err);
                assert(/ECONNREFUSED/.test(err.message), 'should be an error');
                done();
            })
            // Just in case we still have an error.
            .catch(done);
    });
});

您需要做的就是触发http请求中的任何旧错误。

说实话,我可能会换用request,因为它会为你处理一些低级别的东西。然后,您可以使用nock提供虚假回复进行测试。