npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

moc-socket

v0.2.0

Published

Websocket mocking utility

Downloads

28

Readme

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