]> git.proxmox.com Git - mirror_novnc.git/blob - tests/fake.websocket.js
Add eslint and fix reported issues
[mirror_novnc.git] / tests / fake.websocket.js
1 import Base64 from '../core/base64.js';
2
3 // PhantomJS can't create Event objects directly, so we need to use this
4 function make_event(name, props) {
5 var evt = document.createEvent('Event');
6 evt.initEvent(name, true, true);
7 if (props) {
8 for (var prop in props) {
9 evt[prop] = props[prop];
10 }
11 }
12 return evt;
13 }
14
15 export default function FakeWebSocket (uri, protocols) {
16 this.url = uri;
17 this.binaryType = "arraybuffer";
18 this.extensions = "";
19
20 if (!protocols || typeof protocols === 'string') {
21 this.protocol = protocols;
22 } else {
23 this.protocol = protocols[0];
24 }
25
26 this._send_queue = new Uint8Array(20000);
27
28 this.readyState = FakeWebSocket.CONNECTING;
29 this.bufferedAmount = 0;
30
31 this.__is_fake = true;
32 }
33
34 FakeWebSocket.prototype = {
35 close: function (code, reason) {
36 this.readyState = FakeWebSocket.CLOSED;
37 if (this.onclose) {
38 this.onclose(make_event("close", { 'code': code, 'reason': reason, 'wasClean': true }));
39 }
40 },
41
42 send: function (data) {
43 if (this.protocol == 'base64') {
44 data = Base64.decode(data);
45 } else {
46 data = new Uint8Array(data);
47 }
48 this._send_queue.set(data, this.bufferedAmount);
49 this.bufferedAmount += data.length;
50 },
51
52 _get_sent_data: function () {
53 var res = new Uint8Array(this._send_queue.buffer, 0, this.bufferedAmount);
54 this.bufferedAmount = 0;
55 return res;
56 },
57
58 _open: function (data) {
59 this.readyState = FakeWebSocket.OPEN;
60 if (this.onopen) {
61 this.onopen(make_event('open'));
62 }
63 },
64
65 _receive_data: function (data) {
66 this.onmessage(make_event("message", { 'data': data }));
67 }
68 };
69
70 FakeWebSocket.OPEN = WebSocket.OPEN;
71 FakeWebSocket.CONNECTING = WebSocket.CONNECTING;
72 FakeWebSocket.CLOSING = WebSocket.CLOSING;
73 FakeWebSocket.CLOSED = WebSocket.CLOSED;
74
75 FakeWebSocket.__is_fake = true;
76
77 FakeWebSocket.replace = function () {
78 if (!WebSocket.__is_fake) {
79 var real_version = WebSocket;
80 // eslint-disable-next-line no-global-assign
81 WebSocket = FakeWebSocket;
82 FakeWebSocket.__real_version = real_version;
83 }
84 };
85
86 FakeWebSocket.restore = function () {
87 if (WebSocket.__is_fake) {
88 // eslint-disable-next-line no-global-assign
89 WebSocket = WebSocket.__real_version;
90 }
91 };