Mock network requests with nock through a proxy - perfect for real-life environments like end-to-end tests on a real browser.
npm install nock-proxy
Nock overrides the http.request
function of the node process it is running in.
This means that we can spawn a simple pass-through proxy server which will reply
with a mock if said mock is being expected via nock.
const nock = require("nock")
const nockProxy = require("nock-proxy")
// Launch the proxy server on your desired port on localhost.
// Don't forget to setup your browser to use this proxy.
nockProxy(8081)
// Setup your mocks via nock, as usual. Use the option allowUnmocked
// to avoid errors from unexpected requests.
nock("http://www.example.de", { allowUnmocked: true })
.get(/.*/)
.reply(219, {
hello: "world",
})
nock-proxy turns end-to-end tests into integration tests: Simply set up the browser to pass through nock-proxy for having mocks like in an integration test environment. Don't pass through the proxy for using real-world network requests.