{"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.","language":"javascript","status":"active","last_verified":"Sun Apr 19","install":{"commands":["npm install mock-socket"],"cli":null},"imports":["import { Server } from 'mock-socket';","import { WebSocket } from 'mock-socket';","import { SocketIO } from 'mock-socket';"],"auth":{"required":false,"env_vars":[]},"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`.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}