Skip to content

Commit

Permalink
fix(WebSocketSubject): Check to see if WebSocket is in root before us…
Browse files Browse the repository at this point in the history
…ing it
  • Loading branch information
Bryan Bonnet committed May 14, 2018
1 parent dc66731 commit f36cbe2
Show file tree
Hide file tree
Showing 2 changed files with 47 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
7 changes: 5 additions & 2 deletions src/internal/observable/dom/WebSocketSubject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ReplaySubject } from '../../ReplaySubject';
import { Observer, NextObserver } from '../../types';
import { tryCatch } from '../../util/tryCatch';
import { errorObject } from '../../util/errorObject';
import { root } from '../../util/root';

export interface WebSocketSubjectConfig<T> {
/** The url of the socket server to connect to */
Expand Down Expand Up @@ -80,7 +81,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 +91,10 @@ export class WebSocketSubject<T> extends AnonymousSubject<T> {
}
}
}
if (!config.WebSocketCtor) {

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

0 comments on commit f36cbe2

Please sign in to comment.