Created
June 4, 2023 15:34
-
-
Save rluvaton/22d5efab2da5a44f715c92b5e4ec77ec to your computer and use it in GitHub Desktop.
Nock allow connections to servers that the current process start them
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import nock from 'nock'; | |
import { Server } from 'http'; | |
const kHttpServerListen = Symbol('kHttpServerListen'); | |
const openServerPorts = new Set<number>(); | |
function allowRemoteHttpRequestsOnlyToOurServer() { | |
nock.disableNetConnect(); | |
nock.enableNetConnect(host => { | |
let hostAsUrl: URL; | |
// If having protocol | |
if (/^[\w\d]+:\/\//m.test(host)) { | |
hostAsUrl = new URL(host); | |
} else { | |
// noinspection HttpUrlsUsage - disable webstorm want the protocol to be https | |
hostAsUrl = new URL(`http://${host}`); | |
} | |
let port = hostAsUrl.port; | |
// Setting the value to the default port of the url protocol will result in the port value becoming the empty string ('') | |
// From https://nodejs.org/api/url.html#urlport | |
if (port === '') { | |
switch (hostAsUrl.protocol) { | |
case 'http': | |
port = '80'; | |
break; | |
case 'https': | |
port = '443'; | |
break; | |
} | |
} | |
return openServerPorts.has(parseInt(port)); | |
}); | |
// Override http server listen request so we could enable http requests to our HTTP server | |
// Using symbol to make sure we don't override existing methods | |
(Server.prototype as any)[kHttpServerListen] = Server.prototype.listen; | |
Server.prototype.listen = function(...args) { | |
const listenResult = (this as any)[kHttpServerListen](...args); | |
const listenedPort = listenResult.address().port; | |
openServerPorts.add(listenedPort); | |
listenResult.once('close', () => openServerPorts.delete(listenedPort)); | |
return listenResult; | |
}; | |
} | |
beforeAll(() => { | |
allowRemoteHttpRequestsOnlyToOurServer(); | |
}) | |
afterAll(() => { | |
Server.prototype.listen = (Server.prototype as any)[kHttpServerListen]; | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment