Skip to content

Commit

Permalink
fix(WebSocketSubject): Check to see if WebSocket exists in global sco…
Browse files Browse the repository at this point in the history
…pe (#3694)

before using it
  • Loading branch information
bbonnet authored and benlesh committed May 21, 2018
1 parent 7cff11c commit 2db0788
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
42 changes: 42 additions & 0 deletions spec/observables/dom/webSocket-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,48 @@ describe('webSocket', () => {
]);
});
});

describe('node constructor', () => {

it('should send and receive messages', () => {
let messageReceived = false;
const subject = webSocket<string>(<any>{
url: 'ws://mysocket',
WebSocketCtor: (url: string, protocol: string): MockWebSocket => {
return new MockWebSocket(url, protocol);
}
});

subject.next('ping');

subject.subscribe(x => {
expect(x).to.equal('pong');
messageReceived = true;
});

const socket = MockWebSocket.lastSocket;
expect(socket.url).to.equal('ws://mysocket');

socket.open();
expect(socket.lastMessageSent).to.equal(JSON.stringify('ping'));

socket.triggerMessage(JSON.stringify('pong'));
expect(messageReceived).to.be.true;

subject.unsubscribe();
});

it('should handle constructor errors if no WebSocketCtor', () => {

expect(() => {
const subject = webSocket<string>(<any>{
url: 'ws://mysocket'
});
}).to.throw('no WebSocket constructor can be found');

});
});

});

class MockWebSocket {
Expand Down
6 changes: 4 additions & 2 deletions src/internal/observable/dom/WebSocketSubject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ export class WebSocketSubject<T> extends AnonymousSubject<T> {
this.source = urlConfigOrSource as Observable<T>;
} else {
const config = this._config = { ...DEFAULT_WEBSOCKET_CONFIG };
config.WebSocketCtor = WebSocket;
this._output = new Subject<T>();
if (typeof urlConfigOrSource === 'string') {
config.url = urlConfigOrSource;
Expand All @@ -91,7 +90,10 @@ export class WebSocketSubject<T> extends AnonymousSubject<T> {
}
}
}
if (!config.WebSocketCtor) {

if (!config.WebSocketCtor && WebSocket) {
config.WebSocketCtor = WebSocket;
} else if (!config.WebSocketCtor) {
throw new Error('no WebSocket constructor can be found');
}
this.destination = new ReplaySubject();
Expand Down

0 comments on commit 2db0788

Please sign in to comment.