1
|
|
|
import {SocketIO as BaseSocketIOConstructor, Server as BaseServer} from 'mock-socket' |
2
|
|
|
import {createMessageEvent} from 'mock-socket/dist/event-factory' |
3
|
|
|
import cloneDeepWith from 'lodash/cloneDeepWith' |
4
|
|
|
|
5
|
|
|
export class Server extends BaseServer { |
6
|
|
|
// SocketIO sends server (this) as first arg to connection & connect events, this fixes it |
7
|
|
|
dispatchEvent(event, ...customArguments) { |
8
|
|
|
if (customArguments[0] && customArguments[0] === this) { |
9
|
|
|
customArguments.shift() |
10
|
|
|
} |
11
|
|
|
return super.dispatchEvent(event, ...customArguments) |
12
|
|
|
} |
13
|
|
|
} |
14
|
|
|
|
15
|
|
|
// SocketIO class isn't exposed |
16
|
|
|
let serverInstance = new Server('dummy') |
17
|
|
|
let instance = new BaseSocketIOConstructor('dummy') |
18
|
|
|
const BaseSocketIO = Object.getPrototypeOf(instance).constructor |
19
|
|
|
instance.on('connect', () => { |
20
|
|
|
instance.close() |
21
|
|
|
serverInstance.close() |
22
|
|
|
}) |
23
|
|
|
// GG |
24
|
|
|
|
25
|
|
|
function cloneCustomiser(arg) { |
26
|
|
|
if (typeof arg === 'function') { |
27
|
|
|
return function (...args) { |
28
|
|
|
args = cloneDeepWith(args, cloneCustomiser) |
29
|
|
|
return arg(...args) |
30
|
|
|
} |
31
|
|
|
} |
32
|
|
|
return undefined |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
export class SocketIO extends BaseSocketIO { |
36
|
|
|
|
37
|
|
|
// Allow more than 1 arg |
38
|
|
|
emit(event, ...data) { |
39
|
|
|
if (this.readyState !== BaseSocketIO.OPEN) { |
40
|
|
|
throw new Error('SocketIO is already in CLOSING or CLOSED state') |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
// Emulate connection by re-creating all objects |
44
|
|
|
data = cloneDeepWith(data, cloneCustomiser) |
45
|
|
|
|
46
|
|
|
const messageEvent = createMessageEvent({ |
47
|
|
|
type: event, |
48
|
|
|
origin: this.url, |
49
|
|
|
data |
50
|
|
|
}) |
51
|
|
|
|
52
|
|
|
// Dispatch on self since the event listeners are added to per connection |
53
|
|
|
this.dispatchEvent(messageEvent, ...data) |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
once(type, callback) { |
57
|
|
|
const wrapped = (...args) => { |
58
|
|
|
this.removeEventListener(type, wrapped) |
59
|
|
|
return callback(...args) |
60
|
|
|
} |
61
|
|
|
return this.on(type, wrapped) |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
off(...args) { |
65
|
|
|
this.removeEventListener(...args) |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|