From c6ac3b6abedcf85342acb2200890a1aa4e310a6a Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Tue, 29 Oct 2019 07:51:12 +0100 Subject: [PATCH] restore autostart when using fire-and-forget promises. --- README.md | 2 ++ index.js | 10 +++++++++- test/test.js | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4399d64..3c3fabb 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,8 @@ Injects a fake request into an HTTP server. - `close` - whether the request will emit a `close` event. Defaults to `undefined`, meaning no `close` event will be emitted. - `validate` - Optional flag to validate this options object. Defaults to `true`. - `server` - Optional http server. It is used for binding the `dispatchFunc`. + - `autoStart` - Automatically start the request as soon as the method + is called. It is only valid when not passing a callback. Defaults to `true`. - `callback` - the callback function using the signature `function (err, res)` where: - `err` - error object - `res` - a response object where: diff --git a/index.js b/index.js index 78fa95b..cc52ff9 100644 --- a/index.js +++ b/index.js @@ -109,6 +109,14 @@ function Chain (dispatch, option) { this.dispatch = dispatch this._hasInvoked = false this._promise = null + + if (this.option.autoStart !== false) { + process.nextTick(() => { + if (!this._hasInvoked) { + this.end() + } + }) + } } const httpMethods = [ @@ -170,8 +178,8 @@ Object.getOwnPropertyNames(Promise.prototype).forEach(method => { if (this._hasInvoked === true) { throw new Error(errorMessage) } - this._promise = doInject(this.dispatch, this.option) this._hasInvoked = true + this._promise = doInject(this.dispatch, this.option) } return this._promise[method](...args) } diff --git a/test/test.js b/test/test.js index 667a184..222570f 100644 --- a/test/test.js +++ b/test/test.js @@ -1264,6 +1264,43 @@ test('Response.json() should throw an error if the payload is not of valid JSON }) }) +test('promise api should auto start (fire and forget)', (t) => { + t.plan(1) + + function dispatch (req, res) { + t.pass('dispatch called') + res.writeHead(200, { 'Content-Type': 'text/plain' }) + res.end() + } + + inject(dispatch, 'http://example.com:8080/hello') +}) + +test('disabling autostart', (t) => { + t.plan(3) + + let called = false + + function dispatch (req, res) { + t.pass('dispatch called') + called = true + res.writeHead(200, { 'Content-Type': 'text/plain' }) + res.end() + } + + const p = inject(dispatch, { + url: 'http://example.com:8080/hello', + autoStart: false + }) + + setImmediate(() => { + t.equal(called, false) + p.then(() => { + t.equal(called, true) + }) + }) +}) + function getTestStream (encoding) { const word = 'hi' let i = 0