7

I am using Nock with Mocha, and want to check that certain headers exist on a request. I don't care about the other headers, and I don't care about the specific content of the headers whose existence I'm checking for. Is there an easy way to do this? .matchHeader() passes when the specific header is absent, and reqheaders fails unless I specify all the header fields.

Boris K
  • 2,748
  • 5
  • 36
  • 68

1 Answers1

7

reqheaders is the right approach with this.

I'm not sure what issue you came across, but not all the headers need to be supplied. Only the ones that are required for a match.

The other nice feature of reqheaders is that the value can be a function returning a boolean. Since you don't care about the actual value of the headers, returning true has the effect of matching if the header simply exists.

const scope = nock('http://www.example.com', {
  reqheaders: {
    'x-one': () => true,
  }
}).get('/').reply(200, 'match!')


const reqOpts = {
  hostname: 'www.example.com',
  path: '/',
  method: 'GET',
  headers: {
    'X-One': 'hello world',
    'X-Two': 'foo bar',
    'Content-Type': 'application/json',
  }
}

const req = http.request(reqOpts, res => {
  console.log("##### res status", res.statusCode)

  res.on('data', (chunk) => {
    console.log("##### chunk", chunk.toString())
  })
})

req.end()
scope.done()
Matt R. Wilson
  • 5,770
  • 5
  • 25
  • 44