{"id":11345,"library":"mock-socket","title":"WebSocket and Socket.IO Mocking Library","description":"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.","status":"active","version":"9.3.1","language":"javascript","source_language":"en","source_url":"https://github.com/thoov/mock-socket","tags":["javascript","websockets","mock","mocksocket","sockets"],"install":[{"cmd":"npm install mock-socket","lang":"bash","label":"npm"},{"cmd":"yarn add mock-socket","lang":"bash","label":"yarn"},{"cmd":"pnpm add mock-socket","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primary class for creating a mock WebSocket server. CommonJS `require` is supported but ESM `import` is preferred in modern Node.js environments.","wrong":"const Server = require('mock-socket').Server;","symbol":"Server","correct":"import { Server } from 'mock-socket';"},{"note":"The mock WebSocket client class, distinct from the global `WebSocket`. Not a default export. Used to manually create mock WebSocket clients or to replace the global `window.WebSocket`.","wrong":"import WebSocket from 'mock-socket';","symbol":"WebSocket","correct":"import { WebSocket } from 'mock-socket';"},{"note":"Provides a mock `io` constructor for Socket.IO clients. This symbol must be assigned to the global `window.io` for Socket.IO clients to use it.","wrong":"import { io } from 'mock-socket';","symbol":"SocketIO","correct":"import { SocketIO } from 'mock-socket';"}],"quickstart":{"code":"import { Server } from 'mock-socket';\n\n// Simulate a client-side application that uses WebSocket\nclass WebSocketClientApp {\n  constructor(url) {\n    this.messages = [];\n    this.connection = new WebSocket(url);\n\n    this.connection.onopen = () => {\n      console.log('Client connected to:', url);\n    };\n\n    this.connection.onmessage = event => {\n      console.log('Client received:', event.data);\n      this.messages.push(event.data);\n    };\n\n    this.connection.onclose = () => {\n      console.log('Client disconnected');\n    };\n\n    this.connection.onerror = error => {\n      console.error('Client error:', error.message);\n    };\n  }\n\n  sendMessage(message) {\n    this.connection.send(message);\n  }\n}\n\nasync function runMockTest() {\n  const fakeURL = 'ws://localhost:8080';\n  // Create a mock server instance\n  const mockServer = new Server(fakeURL);\n\n  // Listen for connections to the mock server\n  mockServer.on('connection', socket => {\n    console.log('Mock server: client connected!');\n    // Listen for messages from the connected client\n    socket.on('message', data => {\n      console.log('Mock server received from client:', data);\n      if (data === 'hello server') {\n        socket.send('hello client from mock server!');\n      }\n    });\n\n    // Simulate the server closing the connection after a delay\n    setTimeout(() => {\n      socket.close();\n    }, 500);\n  });\n\n  // Instantiate the client app, which will attempt to connect to the fakeURL\n  const app = new WebSocketClientApp(fakeURL);\n  app.sendMessage('hello server');\n\n  // Wait for some asynchronous operations to complete\n  await new Promise(resolve => setTimeout(resolve, 1000));\n\n  console.log('Messages received by client:', app.messages);\n  // Assertions would go here in a real test runner\n  if (app.messages.includes('hello client from mock server!')) {\n    console.log('Test passed: Client received expected message.');\n  } else {\n    console.error('Test failed: Client did not receive expected message.');\n  }\n\n  // Clean up the mock server\n  mockServer.stop();\n  console.log('Mock server stopped.');\n}\n\n// To run this example in a Node.js environment, you might need to globally stub WebSocket\n// If running in a browser environment or a testing framework that stubs globals, this might be optional.\n// For Node.js, ensure `global.WebSocket` is available or pass `{ mock: false }` to Server\n// and manually assign `global.WebSocket = WebSocket;`\n\n// In a test runner like Jest, you might do:\n// beforeAll(() => { global.WebSocket = require('mock-socket').WebSocket; });\n// afterAll(() => { delete global.WebSocket; });\n// For this standalone example, we'll assume a context where WebSocket is available or shimmed.\n// Or, if your client code explicitly imports WebSocket:\n// const { WebSocket } = require('mock-socket'); // or import { WebSocket } from 'mock-socket';\n\nrunMockTest();","lang":"typescript","description":"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`."},"warnings":[{"fix":"Update `mockServer.on('connection', socket => { ... })` to use the `socket` argument directly for sending messages (`socket.send()`) and listening for client messages (`socket.on('message', ...)`) instead of assuming the server instance.","message":"In version 8.0.0, the `connection` event listener on the `Server` instance changed its signature. The first argument is now a `socket` reference (the individual client connection) instead of the `server` instance. This allows direct communication with the connected client.","severity":"breaking","affected_versions":">=8.0.0"},{"fix":"Ensure your project's Node.js environment is version 8 or higher. Upgrade Node.js if necessary.","message":"Node.js 6 support was dropped in version 8.1.0, and subsequently in 9.0.0, which now requires Node.js >= 8.","severity":"breaking","affected_versions":">=8.1.0, >=9.0.0"},{"fix":"To disable automatic global stubbing, pass `{ mock: false }` to the `Server` constructor: `new Server(url, { mock: false })`. You can then manually stub `window.WebSocket = WebSocket;` when and where needed, providing more control.","message":"By default, creating a `new Server()` instance will automatically stub out the global `WebSocket` object, which is restored when the server stops. This can lead to unexpected behavior if multiple `Server` instances are created without proper management or if you need to use the real `WebSocket` in parallel.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"When testing Socket.IO applications, thoroughly verify that `mock-socket` covers the specific Socket.IO features your client code relies on. For complex Socket.IO interactions, consider testing against a real (even if minimal) Socket.IO server or explore alternative mocking strategies if limitations are encountered.","message":"Socket.IO support in `mock-socket` is noted as limited. Not all Socket.IO features or complex scenarios may be fully supported or behave identically to a real Socket.IO server.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure that `mock-socket`'s global stubbing is active by creating a `new Server(url)` instance before the client code runs. If using `{ mock: false }`, manually assign `global.WebSocket = WebSocket;` (or `window.WebSocket` in a browser-like test environment) to the mock `WebSocket` from `mock-socket`.","cause":"When running client-side code (e.g., a React app test) that uses the global `WebSocket` object in a Node.js environment (like Jest), the `WebSocket` global might not be present unless explicitly polyfilled or mocked by `mock-socket`.","error":"Error: WebSocket is not defined"},{"fix":"Ensure your `tsconfig.json` includes `\"lib\": [\"dom\", \"es2017\"]` (or appropriate ES version) to provide standard DOM type definitions. This was a known issue in older `mock-socket` versions that was fixed in 8.0.5.","cause":"This error typically occurs in TypeScript projects when the TypeScript environment or `lib` settings are not correctly configured to include DOM types that define `USVString`.","error":"Cannot find name 'USVString'."},{"fix":"Verify that you are using the correct mock for the client type: `WebSocket` for raw WebSockets and `SocketIO` (assigned to `window.io`) for Socket.IO clients. Ensure your client-side code is calling the appropriate methods (`.onmessage` for `WebSocket`, `.on('event')` for Socket.IO).","cause":"This error usually happens when attempting to use Socket.IO-style event listeners (`.on('event', ...)`) on a standard `WebSocket` mock, or vice versa, or if `window.io` was not correctly stubbed for a Socket.IO client.","error":"TypeError: app.connection.on is not a function"}],"ecosystem":"npm"}