Skip to content

Virus288/MocSocket

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MocSocket - mock websocket connection with ease

I was looking for simple package to mock websocket server and generate clients. Something as easy as superTest. I've created it myself

TLDR:

  1. Supported servers
  2. How to use 2.1. Initialize 2.2. Clients
  3. Examples 3.1. Generate client and connect 3.2. Send messages 3.3. Read client's messages
  4. TODO

1. Supported servers:

  • ws. Tested on version 8+
  • socket.io. Tested on version 4.7+

2. How to use

2.1 Initialize

2.1.1 Socket.io

// 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);

2.1.2 Ws

// Create new ws server without port
const server = new Websocket.Server({
  noServer: true,
});

// Create new instance of MocSocket
const mock = MocSocket.createWsClient(server);

2.2 Clients

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)

2.2.1 Events

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

2.3 Sending messages

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

Ws

await client.sendMessage('Test')

Socket.io

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.

3. Examples

You can find detailed examples in __tests__ folder in this repo, alongside simplified servers in servers folder. Here are few basic examples:

3.1 Generate client and connect - simple client

Ws

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"))

Socket.io

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"))

3.2 Generate client and connect - client

Ws

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()

Socket.io

this.httpServer = http.createServer();
this.server = new Server(this.httpServer, {
  transports: ['websocket']
});

const mock = MocSocket.createSocketIoServer(server);
const client = mock.createClient()
await client.connect()

3.3 Send messages - simple client

Ws

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')
})

Socket.io

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')
})

3.3 Send messages - client

Ws

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')

Socket.io

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')

3.4 Read client's messages - simple client

Ws

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)
})

Socket.io

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)
})

3.5 Read client's messages - client

Ws

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')

Socket.io

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)

3.6 Create client with bearer token in cookies - simple client

Ws

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"))

Socket.io

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"))

3.7 Create client with bearer token in cookies - client

Ws

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()

Socket.io

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()

3.8 Create client with bearer token in headers - simple client

Ws

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"))

Socket.io

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"))

3.9 Create client with bearer token in headers - client

Ws

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()

Socket.io

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()

About

Websocket mocking utility for node.js

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published