Skip to content

Commit

Permalink
fix(typescript): support nock(new URL('https://example.test/'))` (#2526
Browse files Browse the repository at this point in the history
)
  • Loading branch information
samhh committed Oct 10, 2023
1 parent feaa66f commit 6987327
Show file tree
Hide file tree
Showing 42 changed files with 316 additions and 311 deletions.
6 changes: 3 additions & 3 deletions README.md
Expand Up @@ -1142,7 +1142,7 @@ nock.enableNetConnect(/(amazon|github)\.com/)

// Or a Function
nock.enableNetConnect(
host => host.includes('amazon.com') || host.includes('github.com')
host => host.includes('amazon.com') || host.includes('github.com'),
)

http.get('http://www.amazon.com/')
Expand Down Expand Up @@ -1248,7 +1248,7 @@ nocks.forEach(function (nock) {
/(timestamp):([0-9]+)/g,
function (match, key, value) {
return key + ':' + recordedTimestamp
}
},
)
} else {
return body
Expand Down Expand Up @@ -1467,7 +1467,7 @@ function prepareScope(scope) {
const recordedTimestamp = recordedBodyResult[1]
return body.replace(
/(timestamp):([0-9]+)/g,
(match, key, value) => `${key}:${recordedTimestamp}`
(match, key, value) => `${key}:${recordedTimestamp}`,
)
} else {
return body
Expand Down
4 changes: 2 additions & 2 deletions examples/binary-reply.js
Expand Up @@ -6,7 +6,7 @@ const nock = require('../')

const readFile = function () {
return fs.readFileSync(
path.resolve(__dirname, '../tests/assets/reply_file_2.txt.gz')
path.resolve(__dirname, '../tests/assets/reply_file_2.txt.gz'),
)
}

Expand All @@ -29,7 +29,7 @@ http.get('http://binary.com/binary', function (res) {
console.log(
Buffer.compare(readFile(), buffer) === 0
? 'Received the file.'
: 'Received something else.'
: 'Received something else.',
)
})
})
6 changes: 3 additions & 3 deletions lib/back.js
Expand Up @@ -49,7 +49,7 @@ function Back(fixtureName, options, nockedFn) {
throw new Error(
'Back requires nock.back.fixtures to be set\n' +
'Ex:\n' +
"\trequire(nock).back.fixtures = '/path/to/fixtures/'"
"\trequire(nock).back.fixtures = '/path/to/fixtures/'",
)
}

Expand Down Expand Up @@ -300,8 +300,8 @@ function assertScopes(scopes, fixture) {
format(
'%j was not used, consider removing %s to rerecord fixture',
[].concat(...pending),
fixture
)
fixture,
),
)
}
}
Expand Down
14 changes: 7 additions & 7 deletions lib/common.js
Expand Up @@ -81,7 +81,7 @@ function overrideRequests(newRequest) {

if (requestOverrides[moduleName]) {
throw new Error(
`Module's request already overridden for ${moduleName} protocol.`
`Module's request already overridden for ${moduleName} protocol.`,
)
}

Expand Down Expand Up @@ -126,7 +126,7 @@ function restoreOverriddenRequests() {
module.request = request
module.get = get
debug('- restored request for', proto)
}
},
)
requestOverrides = {}
}
Expand Down Expand Up @@ -206,11 +206,11 @@ function headersFieldNamesToLowerCase(headers, throwOnDuplicate) {
if (lowerCaseHeaders[key] !== undefined) {
if (throwOnDuplicate) {
throw Error(
`Failed to convert header keys to lower case due to field name conflict: ${key}`
`Failed to convert header keys to lower case due to field name conflict: ${key}`,
)
} else {
debug(
`Duplicate header provided in request: ${key}. Only the last value can be matched.`
`Duplicate header provided in request: ${key}. Only the last value can be matched.`,
)
}
}
Expand Down Expand Up @@ -244,7 +244,7 @@ function headersInputToRawArray(headers) {
// but throw an error if there aren't an even number of items in the array
if (headers.length % 2) {
throw new Error(
`Raw headers must be provided as an array with an even number of items. [fieldName, value, ...]`
`Raw headers must be provided as an array with an even number of items. [fieldName, value, ...]`,
)
}
return [...headers]
Expand All @@ -260,7 +260,7 @@ function headersInputToRawArray(headers) {
}

throw new Error(
`Headers must be provided as an array of raw values, a Map, or a plain Object. ${headers}`
`Headers must be provided as an array of raw values, a Map, or a plain Object. ${headers}`,
)
}

Expand Down Expand Up @@ -600,7 +600,7 @@ function deepEqual(expected, actual) {

if (isPlainObject(expected) && isPlainObject(actual)) {
const allKeys = Array.from(
new Set(Object.keys(expected).concat(Object.keys(actual)))
new Set(Object.keys(expected).concat(Object.keys(actual))),
)

return allKeys.every(key => deepEqual(expected[key], actual[key]))
Expand Down
20 changes: 10 additions & 10 deletions lib/intercept.js
Expand Up @@ -151,7 +151,7 @@ function interceptorsFor(options) {

// First try to use filteringScope if any of the interceptors has it defined.
for (const { key, interceptors, allowUnmocked } of Object.values(
allInterceptors
allInterceptors,
)) {
for (const interceptor of interceptors) {
const { filteringScope } = interceptor.__nock_scopeOptions
Expand Down Expand Up @@ -185,7 +185,7 @@ function interceptorsFor(options) {
debug(
`matched base path (${interceptors.length} interceptor${
interceptors.length > 1 ? 's' : ''
})`
})`,
)
return interceptors
}
Expand Down Expand Up @@ -243,7 +243,7 @@ function ErroringClientRequest(error) {
process.nextTick(
function () {
this.emit('error', error)
}.bind(this)
}.bind(this),
)
}

Expand Down Expand Up @@ -272,7 +272,7 @@ function overrideClientRequest() {
// https://github.com/nock/nock/pull/1386
// https://github.com/nock/nock/pull/1440
throw Error(
'Creating a ClientRequest with empty `options` is not supported in Nock'
'Creating a ClientRequest with empty `options` is not supported in Nock',
)
}

Expand Down Expand Up @@ -308,10 +308,10 @@ function overrideClientRequest() {
function () {
const error = new NetConnectNotAllowedError(
options.host,
options.path
options.path,
)
this.emit('error', error)
}.bind(this)
}.bind(this),
)
}
}
Expand Down Expand Up @@ -348,7 +348,7 @@ function isActive() {

function interceptorScopes() {
const nestedInterceptors = Object.values(allInterceptors).map(
i => i.interceptors
i => i.interceptors,
)
return [].concat(...nestedInterceptors).map(i => i.scope)
}
Expand Down Expand Up @@ -389,7 +389,7 @@ function activate() {
// https://github.com/nock/nock/pull/1386
// https://github.com/nock/nock/pull/1440
throw Error(
'Making a request with empty `options` is not supported in Nock'
'Making a request with empty `options` is not supported in Nock',
)
}

Expand All @@ -402,10 +402,10 @@ function activate() {

if (isOn() && interceptors) {
const matches = interceptors.some(interceptor =>
interceptor.matchOrigin(options)
interceptor.matchOrigin(options),
)
const allowUnmocked = interceptors.some(
interceptor => interceptor.options.allowUnmocked
interceptor => interceptor.options.allowUnmocked,
)

if (!matches && allowUnmocked) {
Expand Down
12 changes: 6 additions & 6 deletions lib/intercepted_request_router.js
Expand Up @@ -42,7 +42,7 @@ class InterceptedRequestRouter {
// We use lower-case header field names throughout Nock.
headers: common.headersFieldNamesToLowerCase(
options.headers || {},
false
false,
),
}
this.interceptors = interceptors
Expand Down Expand Up @@ -89,7 +89,7 @@ class InterceptedRequestRouter {
req.setHeader(
// We use lower-case header field names throughout Nock.
'authorization',
`Basic ${Buffer.from(options.auth).toString('base64')}`
`Basic ${Buffer.from(options.auth).toString('base64')}`,
)
}

Expand Down Expand Up @@ -297,16 +297,16 @@ class InterceptedRequestRouter {
const requestBodyIsUtf8Representable =
common.isUtf8Representable(requestBodyBuffer)
const requestBodyString = requestBodyBuffer.toString(
requestBodyIsUtf8Representable ? 'utf8' : 'hex'
requestBodyIsUtf8Representable ? 'utf8' : 'hex',
)

const matchedInterceptor = interceptors.find(i =>
i.match(req, options, requestBodyString)
i.match(req, options, requestBodyString),
)

if (matchedInterceptor) {
matchedInterceptor.scope.logger(
'interceptor identified, starting mocking'
'interceptor identified, starting mocking',
)

matchedInterceptor.markConsumed()
Expand All @@ -329,7 +329,7 @@ class InterceptedRequestRouter {

// Try to find a hostname match that allows unmocked.
const allowUnmocked = interceptors.some(
i => i.matchHostName(options) && i.options.allowUnmocked
i => i.matchHostName(options) && i.options.allowUnmocked,
)

if (allowUnmocked && req instanceof ClientRequest) {
Expand Down
28 changes: 14 additions & 14 deletions lib/interceptor.js
Expand Up @@ -39,13 +39,13 @@ module.exports = class Interceptor {
!uri.startsWith('*')
) {
throw Error(
`Non-wildcard URL path strings must begin with a slash (otherwise they won't match anything) (got: ${uri})`
`Non-wildcard URL path strings must begin with a slash (otherwise they won't match anything) (got: ${uri})`,
)
}

if (!method) {
throw new Error(
'The "method" parameter is required for an intercept call.'
'The "method" parameter is required for an intercept call.',
)
}

Expand All @@ -67,10 +67,10 @@ module.exports = class Interceptor {
// We use lower-case header field names throughout Nock.
this.reqheaders = common.headersFieldNamesToLowerCase(
scope.scopeOptions.reqheaders || {},
true
true,
)
this.badheaders = common.headersFieldsArrayToLowerCase(
scope.scopeOptions.badheaders || []
scope.scopeOptions.badheaders || [],
)

this.delayBodyInMs = 0
Expand Down Expand Up @@ -118,7 +118,7 @@ module.exports = class Interceptor {
// It's not very Javascript-y to throw an error for extra args to a function, but because
// of legacy behavior, this error was added to reduce confusion for those migrating.
throw Error(
'Invalid arguments. When providing a function for the first argument, .reply does not accept other arguments.'
'Invalid arguments. When providing a function for the first argument, .reply does not accept other arguments.',
)
}
this.statusCode = null
Expand Down Expand Up @@ -152,7 +152,7 @@ module.exports = class Interceptor {
// Including all the default headers is safe for our purposes because of the specific headers we introspect.
// A more thoughtful process is used to merge the default headers when the response headers are finally computed.
this.headers = common.headersArrayToObject(
this.rawHeaders.concat(this.scope._defaultReplyHeaders)
this.rawHeaders.concat(this.scope._defaultReplyHeaders),
)

// If the content is not encoded we may need to transform the response body.
Expand Down Expand Up @@ -236,7 +236,7 @@ module.exports = class Interceptor {
"request header field doesn't match:",
key,
header,
reqHeader
reqHeader,
)
return false
}
Expand All @@ -247,7 +247,7 @@ module.exports = class Interceptor {
this.scope.logger(
'attempting match %s, body = %s',
stringify(options),
stringify(body)
stringify(body),
)
}

Expand All @@ -259,7 +259,7 @@ module.exports = class Interceptor {

if (this.method !== method) {
this.scope.logger(
`Method did not match. Request ${method} Interceptor ${this.method}`
`Method did not match. Request ${method} Interceptor ${this.method}`,
)
return false
}
Expand All @@ -286,7 +286,7 @@ module.exports = class Interceptor {
}

const reqHeadersMatch = Object.keys(this.reqheaders).every(key =>
this.reqheaderMatches(options, key)
this.reqheaderMatches(options, key),
)

if (!reqHeadersMatch) {
Expand All @@ -299,13 +299,13 @@ module.exports = class Interceptor {
!this.scope.scopeOptions.conditionally()
) {
this.scope.logger(
'matching failed because Scope.conditionally() did not validate'
'matching failed because Scope.conditionally() did not validate',
)
return false
}

const badHeaders = this.badheaders.filter(
header => header in options.headers
header => header in options.headers,
)

if (badHeaders.length) {
Expand All @@ -322,7 +322,7 @@ module.exports = class Interceptor {
const matchQueries = this.matchQuery({ search })

this.scope.logger(
matchQueries ? 'query matching succeeded' : 'query matching failed'
matchQueries ? 'query matching succeeded' : 'query matching failed',
)

if (!matchQueries) {
Expand Down Expand Up @@ -369,7 +369,7 @@ module.exports = class Interceptor {
"bodies don't match: \n",
this._requestBody,
'\n',
body
body,
)
}
}
Expand Down
4 changes: 2 additions & 2 deletions lib/playback_interceptor.js
Expand Up @@ -29,7 +29,7 @@ function parseFullReplyResult(response, fullReplyResult) {

if (fullReplyResult.length > 3) {
throw Error(
'The array returned from the .reply callback contains too many values'
'The array returned from the .reply callback contains too many values',
)
}

Expand Down Expand Up @@ -257,7 +257,7 @@ function playbackInterceptor({
}

response.rawHeaders.push(
...selectDefaultHeaders(response.rawHeaders, defaultHeaders)
...selectDefaultHeaders(response.rawHeaders, defaultHeaders),
)

// Evaluate functional headers.
Expand Down

0 comments on commit 6987327

Please sign in to comment.