使用 sinon 测试 http 请求错误

Testing an http request error using 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() {}) 语句?我正在尝试使用 mocha、stub 和 streams,但我觉得我根本不了解这些。我似乎无法创建导致该声明的错误请求。

试试这个:

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 because it handles some of the low level stuff for you. Then you can use nock 来提供假的测试响应。