Skip to content

Commit

Permalink
fix: Correct behavior when other libraries override http.get and http…
Browse files Browse the repository at this point in the history
….request (#1868)

Thanks @kennethaasan for finding this fix!

Fix #1836
  • Loading branch information
paulmelnikow committed Feb 7, 2020
1 parent 921eacf commit 22e2fca
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/common.js
Expand Up @@ -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
}
Expand Down
57 changes: 57 additions & 0 deletions tests/test_request_overrider.js
Expand Up @@ -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()
})

0 comments on commit 22e2fca

Please sign in to comment.