Nock: normalizeRequestOption changing host to https:443

Created on 25 Jun 2018  路  3Comments  路  Source: nock/nock

I'm facing an issue where one of my tests failed to match a url, after a few hours of debugging I found that normalizeRequestOption changes the host.

const https = require('https')
const nock = require('nock')

nock('https://fake-host.com')
    .persist()
    .post('/')
    .reply(200, {all: 'good'})

const post_request = https.request({host: 'https://doesnt-matter.com'})

This code fails with

Error: getaddrinfo ENOTFOUND https https:443

What happens in my case is that in lib/common.js::normalizeRequestOptions the options object doesn't have a hostname property, so it takes https://fake-host and takes the https then in line 26 it re-writes the host property with the value that it just re-assigned, so host becomes https:443 and later on the request fails.

Part of my stack trace is
common.overrideRequests -> interceptorsFor

I suspect there is something wrong with my code but haven't been able to spot it, any help please?

Most helpful comment

Hi Miguel. I've been trying to replicate your error and I think I've found your problem.

  • The host you are mocking from the nock function doesn't match the host you are actually sending a post request to.
  • The request function has 'https' set as default so it shouldn't be specified in the host property.
  • The following properties had to be set: method: 'post' and path: '/' in order to have an exact match.

After these points I was able to mock the request with your code

I hope this helps.

All 3 comments

Hi Miguel. I've been trying to replicate your error and I think I've found your problem.

  • The host you are mocking from the nock function doesn't match the host you are actually sending a post request to.
  • The request function has 'https' set as default so it shouldn't be specified in the host property.
  • The following properties had to be set: method: 'post' and path: '/' in order to have an exact match.

After these points I was able to mock the request with your code

I hope this helps.

Thanks a lot @jlilja ! following your suggestions did fix it for me, you rock! :)

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue and add a reference to this one if it鈥檚 related. Thank you!

Was this page helpful?
0 / 5 - 0 ratings