nock: Support for simulating errors

Nock is excellent! Something that would make it even excellenter is if nock could be used to simulate connection level errors:

nock("http://api.example.com")
  .get("/some/path")
  .failWith(new Error("socket hang up"));

Especially since these can be otherwise cumbersome to test. Keep up the good work!

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 19 (1 by maintainers)

Most upvoted comments

In the end i solved it with something like:

nock('http://www.google.com')
  .get('/')
  .replyWithError({code: 'ETIMEDOUT'})

Which looks clean, it does not involve delay and stuff, and as it seems to me it is enough to simulate ETIMEDOUT having in mind that im using request-promise lib where i’m checking for ETIMEDOUT like: if (err.error && err.error.code === 'ETIMEDOUT')

Same can be applied for ENOTFOUND, ECONNRESET, ECONNREFUSED...

Hi Guys I had this same issue with superagent when trying to test timeout, took about a whole weekend to put it together that it is because superagent always retries requests by default, in fact deafult is 3 [http://visionmedia.github.io/superagent/#retrying-requests](see here) , so on the second retry nock has no url to match thats why you get

{ Error: Nock: No match for request {
 "method": "POST",
 "url": "http://someurl.com/",
 "body": "some_string"
}
   at end (/Users/eyo.okon/Sites/node-graphql-client/node_modules/nock/lib/request_overrider.js:260:17)
   at OverriddenClientRequest.RequestOverrider.req.end (/Users/eyo.okon/Sites/node-graphql-client/node_modules/nock/lib/request_overrider.js:160:7)
   at Request._end (/Users/eyo.okon/Sites/node-graphql-client/node_modules/superagent/lib/node/index.js:961:9)
   at RequestBase._retry (/Users/eyo.okon/Sites/node-graphql-client/node_modules/superagent/lib/request-base.js:176:15)
   at Request.callback (/Users/eyo.okon/Sites/node-graphql-client/node_modules/superagent/lib/node/index.js:657:17)
   at RequestBase._timeoutError (/Users/eyo.okon/Sites/node-graphql-client/node_modules/superagent/lib/request-base.js:573:8)
   at Timeout.<anonymous> (/Users/eyo.okon/Sites/node-graphql-client/node_modules/superagent/lib/request-base.js:582:12)
   at ontimeout (timers.js:365:14)
   at tryOnTimeout (timers.js:237:5)   at Timer.listOnTimeout (timers.js:207:5) status: 404, statusCode: 404, response: undefined, retries: 1 }

on setting retry to 0 one gets the correct error, and test passes… 🕺🏾 Hopefully this helps someone

I had the same experience as what mazley93 had using node-request-retry.