2014-10-08 133 views
3

我在当前没有测试的函数中有一个分支。这是一个来自request操作的错误处理程序(使用同名的节点模块)。下面是具体的行:使用Nock和请求模拟HTTP请求错误

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状态代码作为回应,没有身体不在请求回调中导致error,或者我测试了错误的东西。

+0

此问题的结尾有可能返回错误。 https://github.com/pgte/nock/issues/164 – 2014-10-08 05:33:06

回答

0

唯一发现的解决方法是模拟超时

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

source

7

使用replyWithError从DOC:

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

的@ PiotrFryga的回答为我工作,因为我的要求callback(err, resp, body)这种变异实际上是在检查“ETIMEDOUT”错误代码err

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