Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore headers when running a mocked request with nock?

Tags:

node.js

nock

I need to mock a request using nock module, which is issued by a module that adds extra headers (x-md5-checksum). And the request does not match because of those headers.

How do I force nock to ignore this header and match the request anyways?

Thanks.

like image 684
moltar Avatar asked Jun 06 '18 22:06

moltar


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 does Nock work?

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.

What is Nock API?

Nock is an HTTP server mocking and expectations library. You can use this library to test frontend modules that are performing HTTP requests. You can test in isolation because Nock lets you dictate what our API responses will be.


1 Answers

Aaccording to the docs, if reqHeaders is not specified, it will skip them.

If no request headers are specified for mocking then Nock will automatically skip matching of request headers

In case you're validating other headers, and if x-md5-checksum is present, but you don't know it's value, you can use a function or a regex to validate any value, or just a valid md5

nock('http://www.example-com', {
   reqHeaders: {
     'x-md5-checksum': /[a-fA-F0-9]{32}/
     // or
     'x-md5-checksum': value => true // I don't care about the value
   }
})
// or use .matchHeader
.matchHeader('x-md5-checksum', value => true)
.get('/')
.reply(200)
like image 183
Marcos Casagrande Avatar answered Oct 06 '22 06:10

Marcos Casagrande