-
Notifications
You must be signed in to change notification settings - Fork 0
/
MockClient.ts
63 lines (52 loc) · 1.62 KB
/
MockClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// tslint:disable:readonly-keyword no-object-mutation
import { IncomingMessage } from 'http';
import { Socket } from 'net';
import { Server as WSServer } from 'ws';
import { MockPeer } from './MockPeer';
export class MockClient extends MockPeer {
protected readonly socket: Socket;
protected connected = false;
constructor(
private wsServer: WSServer,
private headers: { readonly [key: string]: string } = {},
private url: string = '/',
) {
super();
this.socket = new Socket();
// TODO: Propagate error somehow, instead of silencing it
this.socket.on('error', (hadError) => {
// tslint:disable-next-line:no-console
console.log({ hadError });
});
}
public async connect(): Promise<void> {
if (this.connected) {
throw new Error('Cannot connect to server again');
}
const incomingMessage = new IncomingMessage(this.socket);
incomingMessage.headers = {
...incomingMessage.headers,
...this.headers,
};
incomingMessage.url = this.url;
this.connected = true;
// Only return once the server's own `connection` event handler has been been executed
return new Promise((resolve) => {
this.wsServer.once('connection', resolve);
this.wsServer.emit('connection', this.peerWebSocket, incomingMessage);
});
}
/**
* Connect to server, run `callback` and close the connection.
*
* @param callback The function to execute whilst connected to server
*/
public async use(callback: () => Promise<void>): Promise<void> {
await this.connect();
try {
await callback();
} finally {
this.close();
}
}
}