Skip to content

Commit 9a494da

Browse files
gugupaulmelnikow
authored andcommitted
fix: Fix req.end(cb); prevent TypeError in Node 12 (#1547)
According to the docs, `req.end` can accept callback as a first argument. That's what `got` module does. Closes #1509 ``` request.end([data[, encoding]][, callback])# History data <string> | <Buffer> encoding <string> callback <Function> Returns: <this> Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream. If the request is chunked, this will send the terminating '0\r\n\r\n'. If data is specified, it is equivalent to calling request.write(data, encoding) followed by request.end(callback). If callback is specified, it will be called when the request stream is finished. ```
1 parent 7e03b1f commit 9a494da

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

lib/request_overrider.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,10 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
126126

127127
req.end = function(buffer, encoding, callback) {
128128
debug('req.end')
129+
if (_.isFunction(buffer) && arguments.length === 1) {
130+
callback = buffer
131+
buffer = null
132+
}
129133
if (!req.aborted && !ended) {
130134
req.write(buffer, encoding, function() {
131135
if (typeof callback === 'function') {

tests/test_intercept.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -875,6 +875,38 @@ test('end callback called', t => {
875875
})
876876
})
877877

878+
// https://github.com/nock/nock/issues/1509
879+
test('end callback called when end has callback, but no buffer', t => {
880+
const scope = nock('http://example.test')
881+
.post('/')
882+
.reply(200, 'Hello World!')
883+
884+
let callbackCalled = false
885+
const req = http.request(
886+
{
887+
host: 'example.test',
888+
method: 'POST',
889+
path: '/',
890+
port: 80,
891+
},
892+
function(res) {
893+
t.equal(callbackCalled, true)
894+
t.equal(res.statusCode, 200)
895+
res.on('end', function() {
896+
scope.done()
897+
t.end()
898+
})
899+
// Streams start in 'paused' mode and must be started.
900+
// See https://nodejs.org/api/stream.html#stream_class_stream_readable
901+
res.resume()
902+
}
903+
)
904+
905+
req.end(function() {
906+
callbackCalled = true
907+
})
908+
})
909+
878910
// http://github.com/nock/nock/issues/139
879911
test('finish event fired before end event', t => {
880912
const scope = nock('http://example.test')

0 commit comments

Comments
 (0)