From fa6a2c5bbb1db6398aa089434a06345575ac01b1 Mon Sep 17 00:00:00 2001 From: Nicholas Smith Date: Sun, 17 Nov 2019 01:28:19 -0500 Subject: [PATCH] Adds unit test for ripple#1092, fixes unhandled throw when not connected on send due to upgraded ws module --- src/common/connection.ts | 18 +++++++++++------- test/connection-test.ts | 24 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/src/common/connection.ts b/src/common/connection.ts index 2cbe8f87..d59743d8 100644 --- a/src/common/connection.ts +++ b/src/common/connection.ts @@ -420,13 +420,17 @@ class Connection extends EventEmitter { this._console.log(message) } return new Promise((resolve, reject) => { - this._ws.send(message, undefined, error => { - if (error) { - reject(new DisconnectedError(error.message, error)) - } else { - resolve() - } - }) + try { + this._ws.send(message, undefined, error => { + if (error) { + reject(new DisconnectedError(error.message, error)) + } else { + resolve() + } + }) + } catch (error) { + reject(new DisconnectedError(error.message, error)) + } }) } diff --git a/test/connection-test.ts b/test/connection-test.ts index a15b1a9c..d367bd5f 100644 --- a/test/connection-test.ts +++ b/test/connection-test.ts @@ -160,6 +160,30 @@ describe('Connection', function() { }); }); + it('DisconnectedError on initial _onOpen send', async function() { + // _onOpen previously could throw PromiseRejectionHandledWarning: Promise rejection was handled asynchronously + // do not rely on the api.setup hook to test this as it bypasses the case, disconnect api connection first + await this.api.disconnect(); + + // stub _onOpen to only run logic relevant to test case + this.api.connection._onOpen = () => { + // overload websocket send on open when _ws exists + this.api.connection._ws.send = function(data, options, cb) { + // recent ws throws this error instead of calling back + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + const request = {command: 'subscribe', streams: ['ledger']}; + return this.api.connection.request(request); + } + + try { + await this.api.connect(); + } catch (error) { + assert(error instanceof this.api.errors.DisconnectedError); + assert.strictEqual(error.message, 'WebSocket is not open: readyState 0 (CONNECTING)'); + } + }); + it('ResponseFormatError', function() { this.api.connection._send = function(message) { const parsed = JSON.parse(message);