diff --git a/packages/connection/index.js b/packages/connection/index.js index 881ac528..a533bb3e 100644 --- a/packages/connection/index.js +++ b/packages/connection/index.js @@ -179,6 +179,7 @@ class Connection extends EventEmitter { } _status(status, ...args) { + if (this.status === status) return; this.status = status; this.emit("status", status, ...args); this.emit(status, ...args); @@ -242,8 +243,9 @@ class Connection extends EventEmitter { * https://tools.ietf.org/html/rfc7395#section-3.6 */ async disconnect(timeout = this.timeout) { - if (this.socket) this._status("disconnecting"); + if (!this.socket) return; + this._status("disconnecting"); this.socket.end(); // The 'disconnect' status is set by the socket 'close' listener @@ -281,7 +283,7 @@ class Connection extends EventEmitter { async stop() { const el = await this._end(); this.jid = null; - if (this.status !== "offline") this._status("offline", el); + this._status("offline", el); return el; } diff --git a/packages/connection/test/disconnect.js b/packages/connection/test/disconnect.js index d51885bd..ae6f55b7 100644 --- a/packages/connection/test/disconnect.js +++ b/packages/connection/test/disconnect.js @@ -46,3 +46,10 @@ test("rejects if socket.end throws", (done) => { done(); }); }); + +test("resolves if socket is absent", async () => { + const conn = new Connection(); + conn.socket = null; + + await expect(conn.disconnect()).toResolve(); +}); diff --git a/packages/websocket/lib/Socket.js b/packages/websocket/lib/Socket.js index 018e09d6..3227a11b 100644 --- a/packages/websocket/lib/Socket.js +++ b/packages/websocket/lib/Socket.js @@ -79,7 +79,12 @@ export default class Socket extends EventEmitter { if (WebSocket === WS) { this.socket.send(data, fn); } else { - this.socket.send(data); + try { + this.socket.send(data); + } catch (err) { + fn(err); + return; + } fn(); } }