Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

disabled netconnect should throw if allowunmocked #2456

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 20 additions & 9 deletions lib/intercept.js
Expand Up @@ -405,17 +405,28 @@ function activate() {
)

if (!matches && allowUnmocked) {
let req
if (proto === 'https') {
const { ClientRequest } = http
http.ClientRequest = originalClientRequest
req = overriddenRequest(options, callback)
http.ClientRequest = ClientRequest
// When there is an interceptors and no matching condition in the same base path
// Needs to check connection status and throw instead of making the external call
if (isEnabledForNetConnect(options)) {
let req

if (proto === 'https') {
const { ClientRequest } = http
http.ClientRequest = originalClientRequest
req = overriddenRequest(options, callback)
http.ClientRequest = ClientRequest
} else {
req = overriddenRequest(options, callback)
}
globalEmitter.emit('no match', req)
return req
} else {
req = overriddenRequest(options, callback)
const error = new NetConnectNotAllowedError(
options.host,
options.path
)
return new ErroringClientRequest(error)
}
globalEmitter.emit('no match', req)
return req
}

// NOTE: Since we already overrode the http.ClientRequest we are in fact constructing
Expand Down
13 changes: 13 additions & 0 deletions tests/test_net_connect.js
Expand Up @@ -20,6 +20,19 @@ describe('`disableNetConnect()`', () => {
)
})

it('prevents connection to mocked hosts but allow unmocked active', async () => {
nock.disableNetConnect()

nock('https://same.host.test', { allowUnmocked: true })
.get('/some/path/value')
.reply(200)

await assertRejects(
got('https://same.host.test/some/path/other'),
/Nock: Disallowed net connect for "same.host.test:443\/some\/path\/other"/
)
})

it('prevents connections when no hosts are mocked', async () => {
nock.disableNetConnect()

Expand Down