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.
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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With