Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(WebSocketSubject): Check if WebSocket exists before using it #3694

Merged
merged 1 commit into from
May 21, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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