How to test error in request with Nock?

coolxeo picture coolxeo · Dec 30, 2014 · Viewed 14k times · Source

I want to test the error in a request return. I'm using nock in my tests, how can I force Nock to provoke an error? I want to achieve 100% test coverage and need to test err branch for that

request('/foo', function(err, res) {
  if(err) console.log('boom!');
});

Never enter in the if err branch. Even if hit err is a valid response, my Nock line in test looks like this

nock('http://localhost:3000').get('/foo').reply(400);

edit: thanks to some comments:

  • I'm trying to mock an error in the request. From node manual: https://nodejs.org/api/http.html#http_http_request_options_callback If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object
  • An error code (e.g. 4xx) doesn't define the err variable. I'm trying to mock exactly that, whatever error that defines the err variable and evaluates to true

Answer

Krzysiek Szlapinski picture Krzysiek Szlapinski · May 6, 2015

Use replyWithError. From the docs:

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