WebSocket and Socket.IO Mocking Library

9.3.1 · active · verified Sun Apr 19

mock-socket is a JavaScript library designed for mocking WebSocket and Socket.IO connections, facilitating isolated testing of client-side code that interacts with these protocols. The current stable version is 9.3.1. Releases appear to be driven by feature additions, bug fixes, and dependency updates, with major versions typically indicating breaking API changes or significant environment requirements (like Node.js version bumps). Key differentiators include its ability to intercept and control WebSocket and Socket.IO traffic, allowing developers to simulate server responses, connection states, and various network conditions without needing a real backend. It also offers the flexibility to globally stub the `WebSocket` object or manually inject its mocks, and ships with comprehensive TypeScript definitions for improved developer experience. While it supports Socket.IO, this support is explicitly noted as limited.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of `mock-socket` by setting up a mock WebSocket server, connecting a simulated client, sending messages, and simulating connection closure. This example highlights the `Server` class and its event listeners for `connection` and `message`.

import { Server } from 'mock-socket';

// Simulate a client-side application that uses WebSocket
class WebSocketClientApp {
  constructor(url) {
    this.messages = [];
    this.connection = new WebSocket(url);

    this.connection.onopen = () => {
      console.log('Client connected to:', url);
    };

    this.connection.onmessage = event => {
      console.log('Client received:', event.data);
      this.messages.push(event.data);
    };

    this.connection.onclose = () => {
      console.log('Client disconnected');
    };

    this.connection.onerror = error => {
      console.error('Client error:', error.message);
    };
  }

  sendMessage(message) {
    this.connection.send(message);
  }
}

async function runMockTest() {
  const fakeURL = 'ws://localhost:8080';
  // Create a mock server instance
  const mockServer = new Server(fakeURL);

  // Listen for connections to the mock server
  mockServer.on('connection', socket => {
    console.log('Mock server: client connected!');
    // Listen for messages from the connected client
    socket.on('message', data => {
      console.log('Mock server received from client:', data);
      if (data === 'hello server') {
        socket.send('hello client from mock server!');
      }
    });

    // Simulate the server closing the connection after a delay
    setTimeout(() => {
      socket.close();
    }, 500);
  });

  // Instantiate the client app, which will attempt to connect to the fakeURL
  const app = new WebSocketClientApp(fakeURL);
  app.sendMessage('hello server');

  // Wait for some asynchronous operations to complete
  await new Promise(resolve => setTimeout(resolve, 1000));

  console.log('Messages received by client:', app.messages);
  // Assertions would go here in a real test runner
  if (app.messages.includes('hello client from mock server!')) {
    console.log('Test passed: Client received expected message.');
  } else {
    console.error('Test failed: Client did not receive expected message.');
  }

  // Clean up the mock server
  mockServer.stop();
  console.log('Mock server stopped.');
}

// To run this example in a Node.js environment, you might need to globally stub WebSocket
// If running in a browser environment or a testing framework that stubs globals, this might be optional.
// For Node.js, ensure `global.WebSocket` is available or pass `{ mock: false }` to Server
// and manually assign `global.WebSocket = WebSocket;`

// In a test runner like Jest, you might do:
// beforeAll(() => { global.WebSocket = require('mock-socket').WebSocket; });
// afterAll(() => { delete global.WebSocket; });
// For this standalone example, we'll assume a context where WebSocket is available or shimmed.
// Or, if your client code explicitly imports WebSocket:
// const { WebSocket } = require('mock-socket'); // or import { WebSocket } from 'mock-socket';

runMockTest();

view raw JSON →