Open
Description
Please avoid duplicates
- I checked all open feature requests and none of them matched my request.
Context
I came across a situation where I needed to validate a certain header before all requests and respond with a 400
if the validation failed.
nock('http://localhost')
.matchHeader('X-Request-Id', (val) => String(val).match(/^[A-Fa-f0-9]{32}$/) === null)
.get(/.*/)
.replyWithError({
message: 'Invalid request',
code: 400,
})
.persist();
The validation is HTTP verb agnostic, so the above example would need to be repeated for all verbs.
It would be great to have a convenience method for such cases (e.g .any()
or for the .intercept()
method to accept an array of verbs as the second argument).
Alternatives
Yes, here is the implementation I'm currently using:
function nockAny(scope: nock.Scope, uri: string | RegExp, callback: (interceptor: nock.Interceptor) => nock.Scope) {
const verbs = ['GET', 'PUT', 'HEAD', 'PATCH', 'POST', 'DELETE'];
for (const verb of verbs) {
callback(scope.intercept(uri, verb));
}
}
nockAny(
nock('http://localhost').matchHeader('X-Request-Id', (val) => String(val).match(/^[A-Fa-f0-9]{32}$/) === null),
/.*/,
(interceptor) => {
return interceptor
.replyWithError({
message: 'Invalid request',
code: 400,
})
.persist();
},
);
It works just fine, but it would be great to have a convenience method for this. I'd be happy to submit a PR for it.
If the feature request is accepted, would you be willing to submit a PR?
- yes