8000 fix(WebSocketSubject): Check to see if WebSocket exists in global sco… · ReactiveX/rxjs@2db0788 · GitHub
[go: up one dir, main page]

Skip to content

Commit 2db0788

Browse files
bbonnetbenlesh
authored andcommitted
fix(WebSocketSubject): Check to see if WebSocket exists in global scope (#3694)
before using it
1 parent 7cff11c commit 2db0788

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

spec/observables/dom/webSocket-spec.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -636,6 +636,48 @@ describe('webSocket', () => {
636636
]);
637637
});
638638
});
639+
640+
describe('node constructor', () => {
641+
642+
it('should send and receive messages', () => {
643+
let messageReceived = false;
644+
const subject = webSocket<string>(<any>{
645+
url: 'ws://mysocket',
646+
WebSocketCtor: (url: string, protocol: string): MockWebSocket => {
647+
return new MockWebSocket(url, protocol);
648+
}
649+
});
650+
651+
subject.next('ping');
652+
653+
subject.subscribe(x => {
654+
expect(x).to.equal('pong');
655+
messageReceived = true;
656+
});
657+
658+
const socket = MockWebSocket.lastSocket;
659+
expect(socket.url).to.equal('ws://mysocket');
660+
661+
socket.open();
662+
expect(socket.lastMessageSent).to.equal(JSON.stringify('ping'));
663+
664+
socket.triggerMessage(JSON.stringify('pong'));
665+
expect(messageReceived).to.be.true;
666+
667+
subject.unsubscribe();
668+
});
669+
670+
it('should handle constructor errors if no WebSocketCtor', () => {
671+
672+
expect(() => {
673+
const subject = webSocket<string>(<any>{
674+
url: 'ws://mysocket'
675+
});
676+
}).to.throw('no WebSocket constructor can be found');
677+
678+
});
679+
});
680+
639681
});
640682

641683
class MockWebSocket {

src/internal/observable/dom/WebSocketSubject.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,6 @@ export class WebSocketSubject<T> extends AnonymousSubject<T> {
8080
this.source = urlConfigOrSource as Observable<T>;
8181
} else {
8282
const config = this._config = { ...DEFAULT_WEBSOCKET_CONFIG };
83-
config.WebSocketCtor = WebSocket;
8483
this._output = new Subject<T>();
8584
if (typeof urlConfigOrSource === 'string') {
8685
config.url = urlConfigOrSource;
@@ -91,7 +90,10 @@ export class WebSocketSubject<T> extends AnonymousSubject<T> {
9190
}
9291
}
9392
}
94-
if (!config.WebSocketCtor) {
93+
94+
if (!config.WebSocketCtor && WebSocket) {
95+
config.WebSocketCtor = WebSocket;
96+
} else if (!config.WebSocketCtor) {
9597
throw new Error('no WebSocket constructor can be found');
9698
}
9799
this.destination = new ReplaySubject();

0 commit comments

Comments
 (0)
0