Refuse HTTP request error with Nock and Request

I have a branch in a function that is not currently being tested. This is the error handler from the activity request

(using the node module of the same name). Here is the specific line:

request(url, function (error, response, body) {
  if (error) return cb(error);

      

Here's a test:

  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();
    });
  });

      

Mistake:

Uncaught AssertionError: expected null to exist

      

So either sending the status code 500

as a response without a body does not trigger error

the request in the callback, or I am testing the wrong thing.

+3


source to share


3 answers


Use replyWithError

from doc:



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

      

+7


source


The only workaround I found was to simulate a timeout

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

      



source

0


source


This variation on @ PiotrFryga's answer worked for me, since my query callback(err, resp, body)

actually checked for the "ETIMEDOUT" error code in err

:

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

      

0


source







All Articles