Search code examples
javascriptnode.jsnock

nock doesn't work with request(request-promise)


I'm trying to run a piece of code below:

const nock = require('nock');
const request = require('request-promise');

nock('https://some.api.here.com')
  .get('/objects')
  .matchHeader({})
  .reply(200, []);

request({
  method: 'GET',
  uri: `https://some.api.here.com/objects`,
  headers: {}
});

as a result I see an error:

check/node_modules/nock/lib/request_overrider.js:23
  var key = name.toLowerCase();
                 ^

TypeError: name.toLowerCase is not a function
    at getHeader (/check/node_modules/nock/lib/request_overrider.js:23:18)
    at Object.RequestOverrider.options.getHeader (/check/node_modules/nock/lib/request_overrider.js:125:12)
    at checkHeaders (/check/node_modules/nock/lib/interceptor.js:205:51)
    at Array.every (<anonymous>)
    at Interceptor.match (/check/node_modules/nock/lib/interceptor.js:209:39)
    at /check/node_modules/nock/lib/request_overrider.js:237:26
    at baseFindIndex (/check/node_modules/lodash/lodash.js:823:11)
    at findIndex (/check/node_modules/lodash/lodash.js:7275:14)
    at Function.find (/check/node_modules/lodash/lodash.js:5098:21)
    at end (/check/node_modules/nock/lib/request_overrider.js:236:21)
    at OverriddenClientRequest.RequestOverrider.req.end (/check/node_modules/nock/lib/request_overrider.js:153:7)
    at Request.end (/check/node_modules/request/request.js:1238:12)
    at /check/node_modules/request/request.js:413:12
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
    at Function.Module.runMain (module.js:611:11)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:578:3

Any ideas?

cat package.json
{
  "dependencies": {
    "nock": "^9.0.22",
    "request": "2.31.0",
    "request-promise": "^4.2.2"
  }
}

> node -v
v8.3.0

Solution

  • I think you have to specify a key for the header inside .matchHeader({}), which is actually the header name and it seems like the correct way of using it, is as stated below:

    .matchHeader('accept', 'application/json')

    So in your case you are missing the header name. Source

    You can also take a brief look into the source of this module (the affected line).