{"id":11343,"library":"mock-http-server","title":"Mock HTTP Server for Testing","description":"mock-http-server is a Node.js library designed to create controllable HTTP and HTTPS server mocks, primarily for use in functional and integration tests. It allows developers to define expected incoming requests by method and path, and then configure custom responses including status codes, headers, and body content. The current stable version is 1.4.5, with recent minor releases adding features like request history clearing, improved body parsing for various content types (text/plain, urlencoded), and specific port retrieval methods. Its release cadence appears to be feature-driven, with new functionalities and minor fixes arriving periodically. Key differentiators include its explicit control over request matching and response generation, the ability to inspect received requests for assertions, and support for both HTTP and HTTPS protocols. It aims to provide a reliable and isolated testing environment without actual network calls to external services, allowing for consistent and fast test execution.","status":"active","version":"1.4.5","language":"javascript","source_language":"en","source_url":"https://github.com/spreaker/node-mock-http-server","tags":["javascript"],"install":[{"cmd":"npm install mock-http-server","lang":"bash","label":"npm"},{"cmd":"yarn add mock-http-server","lang":"bash","label":"yarn"},{"cmd":"pnpm add mock-http-server","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The package uses a CommonJS default export, so for ES Modules, use a default import.","wrong":"import { ServerMock } from 'mock-http-server';","symbol":"ServerMock","correct":"import ServerMock from 'mock-http-server';"},{"note":"This is the standard CommonJS import pattern, as shown in the package's examples.","symbol":"ServerMock","correct":"const ServerMock = require('mock-http-server');"},{"note":"When configuring HTTPS, `fs.readFileSync` is used to load certificate files. Ensure `node:fs` is imported for ESM contexts.","wrong":"const server = new ServerMock({ ... }, { key: require('fs').readFileSync('key.pem') });","symbol":"HTTPS Configuration (fs.readFileSync)","correct":"import fs from 'node:fs';\nconst server = new ServerMock({ host: \"localhost\", port: 80 }, { host: \"localhost\", port: 443, key: fs.readFileSync(\"private-key.pem\"), cert: fs.readFileSync(\"certificate.pem\") });"}],"quickstart":{"code":"import ServerMock from 'mock-http-server';\nimport util from 'node:util';\n\ndescribe('Test with Mock HTTP Server', function() {\n\n    // Run an HTTP server on localhost:9000\n    var server = new ServerMock({ host: \"localhost\", port: 9000 });\n\n    const startServer = util.promisify(server.start).bind(server);\n    const stopServer = util.promisify(server.stop).bind(server);\n\n    beforeEach(async () => {\n        await startServer();\n    });\n\n    afterEach(async () => {\n        server.resetHandlers(); // Clear handlers between tests\n        server.clearRequests(); // Clear request history\n        await stopServer();\n    });\n\n    it('should mock a GET request to /resource', async () => {\n        server.on({\n            method: 'GET',\n            path: '/resource',\n            reply: {\n                status:  200,\n                headers: { \"content-type\": \"application/json\" },\n                body:    JSON.stringify({ message: \"hello world from mock\" })\n            }\n        });\n\n        // Simulate an HTTP request\n        const response = await fetch('http://localhost:9000/resource');\n        const data = await response.json();\n\n        expect(response.status).toBe(200);\n        expect(data).toEqual({ message: \"hello world from mock\" });\n\n        // Verify the request was received\n        const requests = server.requests({\n            method: 'GET',\n            path: '/resource'\n        });\n        expect(requests.length).toBe(1);\n    });\n});","lang":"javascript","description":"This quickstart demonstrates how to set up, start, and stop a mock HTTP server, define a request handler, make a request against it, and assert on the response and recorded requests within a test suite (e.g., Jest or Mocha)."},"warnings":[{"fix":"Review any `server.requests()` calls that use multiple filtering conditions. If 'OR' logic is still desired, implement custom filtering using the `filter` option or perform multiple `requests()` calls and combine the results manually.","message":"The behavior of `requests()` filtering with multiple conditions changed from an 'OR' logic to an 'AND' logic in version 1.4.1. This means if you were filtering for requests matching *any* of multiple conditions, your filters will now require *all* conditions to be met, potentially causing existing tests to fail or behave unexpectedly.","severity":"breaking","affected_versions":">=1.4.1"},{"fix":"Always ensure `server.stop()` is called in an `afterAll` or `afterEach` block. For isolated tests, use `server.resetHandlers()` and `server.clearRequests()` in `afterEach` to clean up server state.","message":"Failing to stop the server (with `server.stop()`) or clear handlers/requests (with `server.resetHandlers()` and `server.clearRequests()`) between tests can lead to port conflicts (`EADDRINUSE`) or state leakage, causing intermittent test failures. This is especially common in asynchronous test environments like `beforeEach`/`afterEach` hooks.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"For ES Modules, use `import ServerMock from 'mock-http-server';`. For CommonJS, use `const ServerMock = require('mock-http-server');`.","message":"The package primarily uses CommonJS `require` syntax in its examples. While it can be imported in ESM projects using `import ServerMock from 'mock-http-server';` (due to default export), attempting a named import like `import { ServerMock } from 'mock-http-server';` will fail.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Create a `declarations.d.ts` file in your project to define types for `mock-http-server`, or consider using a different mocking library if strong TypeScript support is a critical requirement. Alternatively, suppress errors with `// @ts-ignore` at the cost of type safety.","message":"There are no official TypeScript type declarations (`.d.ts` files) bundled with `mock-http-server`. This means TypeScript users will need to create their own declaration files or use `@ts-ignore` to suppress type errors, potentially losing type safety for server configuration and request/response handling.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `server.stop()` is reliably called in your test teardown (e.g., `afterEach` or `afterAll`). If the issue persists, choose a different port, or configure the server to use port `0` which lets the OS assign an available port, then retrieve it with `server.getHttpPort()` or `server.getHttpsPort()`.","cause":"The specified port (e.g., 9000) is already in use by another process, or the mock server was not properly stopped after a previous test run.","error":"Error: listen EADDRINUSE :::9000"},{"fix":"Change the import statement to a default import: `import ServerMock from 'mock-http-server';`.","cause":"This error typically occurs in an ES Module context when trying to import `ServerMock` as a named export (`import { ServerMock } from 'mock-http-server';`) when the package actually provides a CommonJS default export.","error":"TypeError: (0 , mock_http_server_1.ServerMock) is not a constructor"},{"fix":"Verify that `server.start()` has completed successfully before making requests. Ensure the client is configured to connect to the correct host and port, especially if you're using dynamic port assignment (e.g., port `0`). Make sure there isn't a firewall blocking the connection.","cause":"The client attempting to connect to the mock server cannot establish a connection. This usually means the mock server was not started, or it was stopped before the client could connect, or it's listening on a different host/port than expected.","error":"Error: connect ECONNREFUSED 127.0.0.1:9000"},{"fix":"Refactor your import statements to use ESM `import ServerMock from 'mock-http-server';`. If you need to mix CommonJS `require` with ESM, you can use `import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);` but this is generally discouraged for package imports.","cause":"You are attempting to use `require()` in a JavaScript file that is treated as an ES Module (e.g., `\"type\": \"module\"` in `package.json` or `.mjs` file extension).","error":"ReferenceError: require is not defined in ES module scope"}],"ecosystem":"npm"}