diff --git a/lib/common.js b/lib/common.js index 59f075928..cbfb6fc38 100644 --- a/lib/common.js +++ b/lib/common.js @@ -99,7 +99,11 @@ function overrideRequests(newRequest) { } // https://nodejs.org/api/http.html#http_http_get_options_callback module.get = function(input, options, callback) { - const req = module.request(input, options, callback) + const req = newRequest(proto, overriddenGet.bind(module), [ + input, + options, + callback, + ]) req.end() return req } diff --git a/tests/test_request_overrider.js b/tests/test_request_overrider.js index 5fe90bbbf..9ca868ce7 100644 --- a/tests/test_request_overrider.js +++ b/tests/test_request_overrider.js @@ -684,3 +684,60 @@ test('Request with `Expect: 100-continue` triggers continue event', t => { req.end(exampleRequestBody) }) }) + +// https://github.com/nock/nock/issues/1836 +test('when http.get and http.request have been overridden before nock overrides them, http.get calls through to the expected method', async t => { + // TODO Investigate why this is needed when it's also in the `afterEach()` + // hook in ./setup. + t.on('end', () => { + nock.restore() + sinon.restore() + }) + + // Obtain the original `http.request()` and stub it out, as a library might. + nock.restore() + const overriddenRequest = sinon.stub(http, 'request').callThrough() + const overriddenGet = sinon.stub(http, 'get').callThrough() + + // Let Nock override them again. + nock.activate() + + const server = http.createServer((request, response) => { + response.writeHead(200) + response.end() + }) + await new Promise(resolve => server.listen(resolve)) + + const req = http.get(`http://localhost:${server.address().port}`) + expect(overriddenGet).to.have.been.calledOnce() + expect(overriddenRequest).not.to.have.been.called() + + req.abort() + server.close() +}) + +// https://github.com/nock/nock/issues/1836 +test('when http.get and http.request have been overridden before nock overrides them, http.request calls through to the expected method', async t => { + t.on('end', () => { + nock.restore() + sinon.restore() + }) + + // Obtain the original `http.request()` and stub it out, as a library might. + nock.restore() + const overriddenRequest = sinon.stub(http, 'request').callThrough() + const overriddenGet = sinon.stub(http, 'get').callThrough() + + // Let Nock override them again. + nock.activate() + + const req = http.request({ + host: 'localhost', + path: '/', + port: 1234, + }) + expect(overriddenRequest).to.have.been.calledOnce() + expect(overriddenGet).not.to.have.been.called() + + req.abort() +})