I was looking for simple package to mock websocket server and generate clients. Something as easy as superTest. I've created it myself
- Supported servers
- How to use 2.1. Initialize 2.2. Clients
- Examples 3.1. Generate client and connect 3.2. Send messages 3.3. Read client's messages
- TODO
// Create new ws server, but do not start it
this.httpServer = http.createServer();
this.server = new Server(this.httpServer, {
transports: ['websocket']
});
// Create new instance of MocSocket
const mock = MocSocket.createSocketIoServer(server);
// Create new ws server without port
const server = new Websocket.Server({
noServer: true,
});
// Create new instance of MocSocket
const mock = MocSocket.createWsClient(server);
There are 2 types of clients you can create.
Simple
const client = mock.createSimpleClient()
client.connect()
Default
const client = mock.createClient()
await client.connect()
Simple client will just connect to server using .connect()
method where client will utilize events by itself
Default client returns promise to make sure that connection passed or failed.
Default client is routing all messages to local variable, providing easy access to received data ( applicable only to ws )
const lastTenMessages = client.getLastMessages(10)
Each client support websocket client events like
client.onMessage((message: WebSocket.RawData | string) => (console.log(JSON.stringify(message))))
client.onError((e: Error) => (console.log(e)))
client.onClose((code: number, message: Buffer) => (console.log(`Closed with code ${code} `, message)))
Event onOpen()
is restricted in default client because instance uses it to properly handle connection. You can
still add another 1 with on('open')
Every event can be disabled with client.disableEvent()
if you prefer not to use .off()
Socket.io server also supports
client.onConnectionError((e: Error) => (console.log(e)))
Which triggers, when client is unable to connect to server
There are 2 ways of sending messages, dependent of type of client. Simple client can send messages
client.sendMessage('Test')
And client can await for reponse
await client.sendMessage('Test')
await client.sendAsyncMessage('Event', 'Message', 'OptionalCallback')
Ws will wait for response, where on socket.io, you can point, to which 'event', client should listen to. For example, you can send message on 'message' and wait for response on responses
. If third param is not provided, client will await for response on the same event.
You can find detailed examples in __tests__
folder in this repo, alongside simplified servers in servers
folder. Here are few basic examples:
const server = new Websocket.Server({
noServer: true,
});
server.on('connection', (ws, req) => {
console.log("User connected")
})
const mock = MocSocket.createWsClient(server);
const client = mock.createSimpleClient()
client.connect()
client.onOpen(() => console.log("Connected"))
this.httpServer = http.createServer();
this.server = new Server(this.httpServer, {
transports: ['websocket']
});
const mock = MocSocket.createSocketIoServer(server);
const client = mock.createSimpleClient()
client.connect()
client.onOpen(() => console.log("Connected"))
const server = new Websocket.Server({
noServer: true,
});
server.on('connection', (ws, req) => {
console.log("User connected")
})
const mock = MocSocket.createWsClient(server);
const client = mock.createClient()
await client.connect()
this.httpServer = http.createServer();
this.server = new Server(this.httpServer, {
transports: ['websocket']
});
const mock = MocSocket.createSocketIoServer(server);
const client = mock.createClient()
await client.connect()
const server = new Websocket.Server({
noServer: true,
});
server.on('connection', (ws, req) => {
console.log("User connected")
ws.on('message', (message: string) => {
console.log("Got user's message")
});
})
const mock = MocSocket.createWsClient(server);
const client = mock.createSimpleClient()
client.connect()
client.onOpen(() => {
client.sendMessage('Test')
})
this.httpServer = http.createServer();
this.server = new Server(this.httpServer, {
transports: ['websocket']
});
this.server.on('connection', (ws) => {
ws.on('message', (m) => {
console.log(m)
})
})
const mock = MocSocket.createSocketIoServer(server);
const client = mock.createSimpleClient()
client.connect()
client.onOpen(() => {
client.sendMessage('message', 'test')
})
const server = new Websocket.Server({
noServer: true,
});
server.on('connection', (ws, req) => {
console.log("User connected")
ws.on('message', (message: string) => {
console.log("Got user's message")
});
})
const mock = MocSocket.createWsClient(server);
const client = mock.createClient()
await client.connect()
client.sendMessage('Test')
this.httpServer = http.createServer();
this.server = new Server(this.httpServer, {
transports: ['websocket']
});
this.server.on('connection', (ws) => {
ws.on('message', (m) => {
console.log(m)
})
})
const mock = MocSocket.createSocketIoServer(server);
const client = mock.createClient()
await client.connect()
client.sendMessage('message', 'test')
const messages = []
const server = new Websocket.Server({
noServer: true,
});
server.on('connection', (ws, req) => {
console.log("User connected")
ws.on('message', (message: string) => {
console.log("Got user's message")
});
})
const mock = MocSocket.createWsClient(server);
const client = mock.createSimpleClient()
client.connect()
client.onOpen(() => {
client.sendMessage('Test')
})
client.onMessage((m) => {
messages.push(m)
})
const messages = []
this.httpServer = http.createServer();
this.server = new Server(this.httpServer, {
transports: ['websocket']
});
this.server.on('connection', (ws) => {
ws.on('message', (m) => {
console.log(m)
})
})
const mock = MocSocket.createSocketIoServer(server);
const client = mock.createSimpleClient()
client.connect()
client.onOpen(() => {
client.sendMessage('message', 'test')
})
client.on('messages', (m) => {
messages.push(m)
})
const server = new Websocket.Server({
noServer: true,
});
server.on('connection', (ws, req) => {
console.log("User connected")
ws.on('message', (message: string) => {
console.log("Got user's message")
});
})
const mock = MocSocket.createWsClient(server);
const client = mock.createClient()
await client.connect()
const message = await client.sendAsyncMessage('Test')
this.httpServer = http.createServer();
this.server = new Server(this.httpServer, {
transports: ['websocket']
});
this.server.on('connection', (ws) => {
ws.on('message', (m) => {
console.log(m)
})
})
const mock = MocSocket.createSocketIoServer(server);
const client = mock.createClient()
await client.connect()
client.on('callback', (m) => {
console.log('new message', m)
})
await client.sendAsyncMessage('message', 'test', callback)
const server = new Websocket.Server({
noServer: true,
});
server.on('connection', (ws, req) => {
console.log("User connected")
})
const mock = MocSocket.createWsClient(server);
const client = mock.createSimpleClient()
client.connect({ headers: { cookie: "randomId=VaryLegitAuthKey;" } });
client.onOpen(() => console.log("Connected"))
this.httpServer = http.createServer();
this.server = new Server(this.httpServer, {
transports: ['websocket']
});
const mock = MocSocket.createSocketIoServer(server);
const client = mock.createSimpleClient()
client.connect({
options: {
transports: ['websocket'],
extraHeaders: {
cookie: 'randomId=123;'
}
}
})
client.onOpen(() => console.log("Connected"))
const server = new Websocket.Server({
noServer: true,
});
server.on('connection', (ws, req) => {
console.log("User connected")
})
const mock = MocSocket.createWsClient(server);
await client.connect({ headers: { cookie: "randomId=VaryLegitAuthKey;" } });
await client.connect()
this.httpServer = http.createServer();
this.server = new Server(this.httpServer, {
transports: ['websocket']
});
const mock = MocSocket.createSocketIoServer(server);
await client.connect({
options: {
transports: ['websocket'],
extraHeaders: {
cookie: 'randomId=123;'
}
}
})
await client.connect()
const server = new Websocket.Server({
noServer: true,
});
server.on('connection', (ws, req) => {
console.log("User connected")
})
const mock = MocSocket.createWsClient(server);
const client = mock.createSimpleClient()
client.connect({ headers: { Authorization: `Bearer VaryRealisticAuthKey` } });
client.onOpen(() => console.log("Connected"))
this.httpServer = http.createServer();
this.server = new Server(this.httpServer, {
transports: ['websocket']
});
const mock = MocSocket.createSocketIoServer(server);
const client = mock.createSimpleClient()
client.connect({
options: {
transports: ['websocket'],
extraHeaders: {
Authorization: "Bearer varyLegitApiKey"
}
}
})
client.onOpen(() => console.log("Connected"))
const server = new Websocket.Server({
noServer: true,
});
server.on('connection', (ws, req) => {
console.log("User connected")
})
const mock = MocSocket.createWsClient(server);
await client.connect({ headers: { Authorization: `Bearer VaryRealisticAuthKey` } });
await client.connect()
this.httpServer = http.createServer();
this.server = new Server(this.httpServer, {
transports: ['websocket']
});
const mock = MocSocket.createSocketIoServer(server);
await client.connect({
options: {
transports: ['websocket'],
extraHeaders: {
Authorization: "Bearer varyLegitApiKey"
}
}
})
await client.connect()