Skip to content
This repository has been archived by the owner on Apr 2, 2024. It is now read-only.

Add WebSocket connected() function #656

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/client/WebSocketClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,44 @@ describe('WebSocketClient', () => {
});
});

describe('connected', () => {
it('returns false when called before the connection is created', done => {
const ws = createWebSocketClient();
expect(ws.connected).toBe(false);
done();
});
it('returns true when called after the connection is created', done => {
const ws = createWebSocketClient();

ws.on(WebSocketEvent.ON_CLOSE, () => {
done();
});

ws.on(WebSocketEvent.ON_OPEN, () => {
expect(ws.connected).toBe(true);

ws.disconnect();
});

ws.connect();
});

it('returns false when called after the connection is closed', done => {
const ws = createWebSocketClient();

ws.on(WebSocketEvent.ON_CLOSE, () => {
expect(ws.connected).toBe(false);
done();
});

ws.on(WebSocketEvent.ON_OPEN, () => {
ws.disconnect();
});

ws.connect();
});
});

describe('constructor', () => {
it('it signals an event when the WebSocket connection is established', done => {
const ws = createWebSocketClient();
Expand Down
9 changes: 9 additions & 0 deletions src/client/WebSocketClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,15 @@ export class WebSocketClient extends EventEmitter {
}
}

/**
* A simple function to determine if the websocket appears to be open.
*
* @returns True if the websocket has been opened and has not closed.
*/
get connected(): boolean {
return undefined !== this.socket;
}

async sendMessage(message: WebSocketRequest): Promise<void> {
if (!this.socket) {
throw new Error(`Failed to send message of type "${message.type}": You need to connect to the WebSocket first.`);
Expand Down