Node.js 使用Nock和request模拟HTTP请求错误

Node.js 使用Nock和request模拟HTTP请求错误,node.js,mocking,request,Node.js,Mocking,Request,我有一个当前未测试的函数分支。这是一个来自请求操作(使用同名节点模块)的错误处理程序。以下是具体的一行: request(url, function (error, response, body) { if (error) return cb(error); 以下是测试: describe("handles errors", function() { it("from the request", function (done) { var api = nock('htt

我有一个当前未测试的函数分支。这是一个来自
请求
操作(使用同名节点模块)的错误处理程序。以下是具体的一行:

request(url, function (error, response, body) {
  if (error) return cb(error);
以下是测试:

  describe("handles errors", function() {
    it("from the request", function (done) {
    var api = nock('http://football-api.com')
                .get('/api/?Action=today&APIKey=' + secrets.APIKey + '&comp_id=1204')
                .reply(500);

    fixture.getFixture(FixtureMock, function (err, fixture) {
      expect(err).to.exist
      done();
    });
  });
规范失败:

Uncaught AssertionError: expected null to exist

因此,发送一个
500
状态代码作为一个没有主体的响应不会在请求回调中导致
错误,或者我测试了错误的东西。

唯一找到的解决方法是模拟超时

nock('http://service.com').get('/down').delayConnection(500).reply(200)
unirest.get('http://service.com/down').timeout(100).end(function(err) {
  // err = ETIMEDOUT
});

使用文档中的
带有错误的回复

nock('http://www.google.com')
   .get('/cat-poems')
   .replyWithError('something awful happened');

@PiotrFryga回答的这个变体对我很有用,因为我的请求
回调(err,resp,body)
实际上是在
err
中检查“ETIMEDOUT”错误代码:

nock('http://www.google.com')
   .get('/cat-poems')
   .replyWithError({code: "ETIMEDOUT"});

此问题的结束可能会返回错误。即使错误条件可能不同,这难道不只是提供一个通用(和预期的)响应吗?也许最好是测试准确的错误条件。