Skip to content

Commit

Permalink
Support req.end with callback only
Browse files Browse the repository at this point in the history
According to docs, `req.end` can accept callback as a first argument. That's what `got` module does.

Fixes nock#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.
```
  • Loading branch information
gugu committed May 9, 2019
1 parent 7e03b1f commit 5498ed4
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/request_overrider.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ function RequestOverrider(req, options, interceptors, remove, cb) {

req.end = function(buffer, encoding, callback) {
debug('req.end')
if (_.isFunction(buffer) && arguments.length === 1) {
callback = buffer
buffer = null
}
if (!req.aborted && !ended) {
req.write(buffer, encoding, function() {
if (typeof callback === 'function') {
Expand Down
32 changes: 32 additions & 0 deletions tests/test_intercept.js
Original file line number Diff line number Diff line change
Expand Up @@ -875,6 +875,38 @@ test('end callback called', t => {
})
})

// https://github.com/nock/nock/issues/1509
test('end callback called when end has callback, but no buffer', t => {
const scope = nock('http://example.test')
.post('/')
.reply(200, 'Hello World!')

let callbackCalled = false
const req = http.request(
{
host: 'example.test',
method: 'POST',
path: '/',
port: 80,
},
function(res) {
t.equal(callbackCalled, true)
t.equal(res.statusCode, 200)
res.on('end', function() {
scope.done()
t.end()
})
// Streams start in 'paused' mode and must be started.
// See https://nodejs.org/api/stream.html#stream_class_stream_readable
res.resume()
}
)

req.end(function() {
callbackCalled = true
})
})

// http://github.com/nock/nock/issues/139
test('finish event fired before end event', t => {
const scope = nock('http://example.test')
Expand Down

0 comments on commit 5498ed4

Please sign in to comment.