Skip to content

Instantly share code, notes, and snippets.

@feliperohdee
Last active April 19, 2016 18:11
Show Gist options
  • Save feliperohdee/ac542e8beae89bc2c2f268718a004a9c to your computer and use it in GitHub Desktop.
Save feliperohdee/ac542e8beae89bc2c2f268718a004a9c to your computer and use it in GitHub Desktop.
import * as _ from 'lodash';
var root = window;
export class MockWebSocket {
static sockets: Array<MockWebSocket> = [];
static get lastSocket(): MockWebSocket {
return _.last(MockWebSocket.sockets);
}
static clearSockets(): void {
MockWebSocket.sockets.length = 0;
}
public sent: Array<any> = [];
public handlers: any = {};
public readyState: number = 0;
public closeCode: any;
public closeReason: any;
constructor(public url: string, public protocol: string) {
MockWebSocket.sockets.push(this);
}
send(data: any): void {
this.sent.push(data);
}
get lastMessageSent(): any {
return _.last(this.sent);
}
triggerClose(e: any): void {
this.readyState = 3;
this.trigger('close', e);
}
triggerError(err: any): void {
this.readyState = 3;
this.trigger('error', err);
}
triggerMessage(data: any): void {
const messageEvent = {
data: data,
origin: 'mockorigin',
ports: undefined,
source: root,
};
this.trigger('message', messageEvent);
}
open(): void {
this.readyState = 1;
this.trigger('open', {});
}
close(code: any, reason: any): void {
if (this.readyState < 2) {
this.readyState = 2;
this.closeCode = code;
this.closeReason = reason;
this.triggerClose({ wasClean: true });
}
}
addEventListener(name: string, handler: any): void {
let lookup = this.handlers[name] = this.handlers[name] || [];
lookup.push(handler);
}
removeEventListener(name: string, handler: any): void {
let lookup = this.handlers[name];
if (lookup) {
_.each(lookup, (l, i) => {
if (l === handler) {
lookup.splice(i, 1);
}
});
}
}
trigger(name: string, e: any) {
if (this[`on${name}`]) {
this[`on${name}`](e);
}
let lookup = this.handlers[name];
if (lookup) {
_.each(lookup, l => l(e));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment