{"id":17694,"library":"http-mockserver","title":"HTTP Mock Server for Node.js","description":"http-mockserver is a Node.js library designed for easily mocking HTTP servers, primarily used for testing purposes. It allows developers to define static or dynamic responses for specific HTTP methods and URIs on a given port. The current stable version is 2.7.21 (as of April 2026). The package appears to have a consistent maintenance cadence, with recent updates (as seen in the changelog for 2025-2026) focusing on dependency vulnerability fixes and minor bug fixes rather than new features or breaking changes. Key differentiators include its simplicity in defining mock endpoints, support for both static responses and dynamic request handlers (using Express-like `req`, `res` objects), and the ability to start a mock server either programmatically within a Node.js process or as a standalone CLI tool. The CLI option allows interaction from non-Node.js clients via a REST API. It also provides utilities for inspecting request logs and waiting for specific requests to simplify assertion logic in tests.","status":"active","version":"2.7.18","language":"javascript","source_language":"en","source_url":"https://github.com/Tradeshift/node-mock-server","tags":["javascript"],"install":[{"cmd":"npm install http-mockserver","lang":"bash","label":"npm"},{"cmd":"yarn add http-mockserver","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-mockserver","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"While the README uses CommonJS `require`, the library ships with both CJS and ESM exports. For modern Node.js environments and TypeScript, prefer the ESM import.","wrong":"const mockServer = require('http-mockserver');","symbol":"mockServer","correct":"import { mockServer } from 'http-mockserver';"},{"note":"The `mockClient` is used for interacting with a `mockServer` that was started externally (e.g., via CLI or `mockServer.start()` in another process). Use ESM imports for consistency.","wrong":"const mockClient = require('http-mockserver');","symbol":"mockClient","correct":"import { mockClient } from 'http-mockserver';"},{"note":"`create` is a method on the `mockServer` object, not a top-level named export. It returns a port-specific mock server instance.","wrong":"import { create } from 'http-mockserver'; const backendService = create(8888);","symbol":"create","correct":"import { mockServer } from 'http-mockserver'; const backendService = mockServer.create(8888);"}],"quickstart":{"code":"import { mockServer } from 'http-mockserver';\n\nasync function setupMocks() {\n  // Start a mock server on a specific port (optional if using `mockServer.create`)\n  // mockServer.start(8080); \n\n  // Static mock for a GET request\n  mockServer.addMock({\n    port: 8080,\n    method: 'GET',\n    uri: '/api/users/123',\n    response: {\n      statusCode: 200,\n      headers: { 'Content-Type': 'application/json' },\n      body: { id: 123, name: 'Alice Smith' }\n    }\n  });\n\n  // Dynamic mock for a POST request with a counter\n  let callCount = 0;\n  mockServer.addMock({\n    port: 8080,\n    method: 'POST',\n    uri: '/api/events',\n    handler: (req, res) => {\n      callCount++;\n      console.log(`Event received. Current count: ${callCount}`);\n      res.status(201).send({ message: `Event processed, call #${callCount}`, payload: req.body });\n    }\n  });\n\n  console.log('Mock servers are set up on port 8080. Try curling:');\n  console.log('curl http://localhost:8080/api/users/123');\n  console.log('curl -X POST -H \"Content-Type: application/json\" -d \\'{\"type\":\"click\"}\\' http://localhost:8080/api/events');\n\n  // Example of using a port-specific instance\n  const authService = mockServer.create(8081);\n  authService.addMock({\n    uri: '/auth/token',\n    method: 'POST',\n    response: { statusCode: 200, body: { accessToken: 'mock-token' } }\n  });\n  console.log('Auth service mock also available on port 8081:');\n  console.log('curl -X POST http://localhost:8081/auth/token');\n\n  // To clean up after tests\n  // mockServer.clearAll();\n  // mockServer.stop(); // Only if mockServer.start was called\n}\n\nsetupMocks();","lang":"typescript","description":"This quickstart demonstrates setting up both static and dynamic HTTP mocks on different ports using `http-mockserver`. It shows how to define responses with specific status codes, headers, and bodies, and how to use a handler function for more complex, stateful mocking. It also illustrates creating port-specific instances."},"warnings":[{"fix":"Ensure your Node.js environment meets the minimum version requirement (>=v16.20.2). Use `nvm` or `volta` to manage Node.js versions if necessary.","message":"The `http-mockserver` requires Node.js v16.20.2 or higher. Earlier Node.js versions may encounter compatibility issues or unfulfilled `engines` requirements during installation.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Choose an unused port for your mocks, or implement logic to dynamically find an available port. Always clean up mocks with `mockServer.clearAll()` or `mockServer.stop()` in your test teardown to free up ports.","message":"When using `mockServer.addMock()`, ensure the specified `port` is available. If another process is already listening on that port (e.g., 8080), the mock server will fail to bind, leading to an 'EADDRINUSE' error. The `mockServer.start()` method also defaults to port 3000, which can conflict.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If managing the mock server within the same process, use `mockServer`. If communicating with a remote or independently launched mock server, configure `mockClient.setServerHost()` and use its API methods.","message":"There's a distinction between `mockServer` (which manages all mocks) and `mockClient` (for interacting with an externally started server). If you're running `http-mockserver` as a standalone CLI process or using `mockServer.start()` in a separate Node process, you must use `mockClient` to add/remove mocks and retrieve logs from your main application.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Change the `port` number in your `addMock` call to an available port. Alternatively, ensure `mockServer.clearAll()` and `mockServer.stop()` are called in your test suite's `afterAll` or `teardown` hooks to prevent port conflicts.","cause":"Attempting to add a mock or start a server on a port that is already in use by another process or a previous uncleaned mock server instance.","error":"Error: listen EADDRINUSE: address already in use :::8080"},{"fix":"Ensure you are using the correct named import: `import { mockServer } from 'http-mockserver';` for ESM or `const { mockServer } = require('http-mockserver');` for CommonJS. `mockServer` is an object, not a class.","cause":"This error typically occurs if `mockServer` was not imported correctly, or if it was instantiated incorrectly (e.g., `new mockServer()` if `mockServer` is an object with static methods).","error":"TypeError: mockServer.addMock is not a function"},{"fix":"Explicitly define the `port` property within each mock object passed to `mockServer.addMock({ port: 8080, ... })`. If you want to avoid specifying the port repeatedly, use `const myMockService = mockServer.create(8080);` and then `myMockService.addMock({ ... });`.","cause":"When using `mockServer.addMock()`, the `port` property is a mandatory part of the mock object, unless you are using an instance created by `mockServer.create(port)`.","error":"Error: Mocks cannot be added on port undefined"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}