diff --git a/spec/observables/dom/webSocket-spec.ts b/spec/observables/dom/webSocket-spec.ts index 854e9369da..6a3e0b6f9c 100644 --- a/spec/observables/dom/webSocket-spec.ts +++ b/spec/observables/dom/webSocket-spec.ts @@ -171,6 +171,32 @@ describe('webSocket', () => { (socket.close).restore(); }); + it('should close the socket when unsubscribed while connecting', () => { + const subject = webSocket('ws://mysocket'); + subject.subscribe(); + const socket = MockWebSocket.lastSocket; + sinon.spy(socket, 'close'); + subject.unsubscribe(); + + expect(socket.close).have.been.called; + expect(socket.readyState).to.equal(3); // closed + + (socket.close).restore(); + }); + + it('should close the socket when subscription is cancelled while connecting', () => { + const subject = webSocket('ws://mysocket'); + const subscription = subject.subscribe(); + const socket = MockWebSocket.lastSocket; + sinon.spy(socket, 'close'); + subscription.unsubscribe(); + + expect(socket.close).have.been.called; + expect(socket.readyState).to.equal(3); // closed + + (socket.close).restore(); + }); + it('should close the socket with a code and a reason when errored', () => { const subject = webSocket('ws://mysocket'); subject.subscribe(); diff --git a/src/internal/observable/dom/WebSocketSubject.ts b/src/internal/observable/dom/WebSocketSubject.ts index 0700382222..c6e4f2e6dd 100644 --- a/src/internal/observable/dom/WebSocketSubject.ts +++ b/src/internal/observable/dom/WebSocketSubject.ts @@ -367,7 +367,7 @@ export class WebSocketSubject extends AnonymousSubject { subscriber.add(() => { const { _socket } = this; if (this._output.observers.length === 0) { - if (_socket && _socket.readyState === 1) { + if (_socket && (_socket.readyState === 1 || _socket.readyState === 0)) { _socket.close(); } this._resetState(); @@ -378,7 +378,7 @@ export class WebSocketSubject extends AnonymousSubject { unsubscribe() { const { _socket } = this; - if (_socket && _socket.readyState === 1) { + if (_socket && (_socket.readyState === 1 || _socket.readyState === 0)) { _socket.close(); } this._resetState();