Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nock.js: how do I check for the existence of a header?

Tags:

node.js

nock

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.

like image 641
Boris K Avatar asked Jan 28 '19 09:01

Boris K


People also ask

How do you pass a header on a nock?

Specifying Request HeadersThe function will be passed the header value. If reqheaders is not specified or if host is not part of it, Nock will automatically add host value to request header. If no request headers are specified for mocking then Nock will automatically skip matching of request headers.

How do I add a header in node JS?

setHeader(name, value) (Added in v0. 4.0) method is an inbuilt application programming interface of the 'http' module which sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced.

What is header in node JS?

The header tells the server details about the request such as what type of data the client, user, or request wants in the response. Type can be html , text , JSON , cookies or others.

What is Nock in Nodejs?

Nock is an HTTP server mocking and expectations library for Node. js. Nock works by overriding the http. request and http. ClientRequest functions, intercepting all requests made to a specified URL and returning specified responses that mimic the data that the real URL would return.


1 Answers

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()
like image 120
Matt R. Wilson Avatar answered Sep 23 '22 06:09

Matt R. Wilson