{"id":16142,"library":"node-mocks-http","title":"Node HTTP Mocks","description":"node-mocks-http is a testing utility for Node.js environments that provides mock implementations of `http.IncomingMessage` (request) and `http.ServerResponse` (response) objects. It is designed to facilitate unit testing of web server applications, particularly those built with frameworks like Express, Next.js, and Koa, by allowing developers to simulate HTTP requests and responses without needing to spin up a full HTTP server. The current stable version is 1.17.2, and the project shows a positive release cadence with recent updates. Key differentiators include its focus on low-level `http` object mocking, bundled TypeScript typings, and explicit support for framework-specific request/response types (e.g., Express, Next.js API routes, Next.js App Router). This makes it suitable for isolating and testing individual route handlers or middleware functions efficiently.","status":"active","version":"1.17.2","language":"javascript","source_language":"en","source_url":"git://github.com/eugef/node-mocks-http","tags":["javascript","mock","stub","dummy","nodejs","js","testing","test","http","typescript"],"install":[{"cmd":"npm install node-mocks-http","lang":"bash","label":"npm"},{"cmd":"yarn add node-mocks-http","lang":"bash","label":"yarn"},{"cmd":"pnpm add node-mocks-http","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency for TypeScript users testing Express.js applications, providing accurate type definitions for mock objects.","package":"@types/express","optional":true},{"reason":"Peer dependency for TypeScript users, providing core Node.js type definitions, including those for http.IncomingMessage and http.ServerResponse.","package":"@types/node","optional":true}],"imports":[{"note":"For modern Node.js projects using ES Modules (`\"type\": \"module\"` in `package.json` or `.mjs` files). CommonJS `require` is still supported but less idiomatic for new projects.","wrong":"const httpMocks = require('node-mocks-http');","symbol":"httpMocks","correct":"import httpMocks from 'node-mocks-http';"},{"note":"Standard CommonJS import pattern. This is shown in the README, indicating its continued support.","symbol":"httpMocks","correct":"const httpMocks = require('node-mocks-http');"},{"note":"These methods are properties of the default `httpMocks` export, not named exports from the package root. Direct destructuring from the package path will fail.","wrong":"import { createRequest } from 'node-mocks-http';","symbol":"createRequest / createResponse","correct":"import httpMocks from 'node-mocks-http';\nconst request = httpMocks.createRequest();"},{"note":"Next.js specific types must be imported from the `next` package, not `node-mocks-http`. `node-mocks-http` uses these as generic type parameters for its mock objects.","wrong":"import { NextApiRequest } from 'node-mocks-http';","symbol":"NextApiRequest / NextApiResponse","correct":"import type { NextApiRequest, NextApiResponse } from 'next';\nimport httpMocks from 'node-mocks-http';\n\nconst mockRequest = httpMocks.createRequest<NextApiRequest>({});"}],"quickstart":{"code":"import httpMocks from 'node-mocks-http';\nimport type { Request, Response } from 'express';\n\n// Imagine this is your Express route handler\nconst routeHandler = function(request: Request, response: Response) {\n    const { id } = request.params;\n    if (id === '42') {\n        response.statusCode = 200;\n        response.setHeader('Content-Type', 'application/json');\n        response.send(JSON.stringify({\n            name: 'Bob Dog',\n            age: 42,\n            email: 'bob@dog.com'\n        }));\n    } else {\n        response.statusCode = 404;\n        response.send('User not found');\n    }\n};\n\ndescribe('routeHandler', () => {\n    it('should return user data for a valid ID', () => {\n        const request = httpMocks.createRequest<Request>({\n            method: 'GET',\n            url: '/user/42',\n            params: {\n                id: '42'\n            }\n        });\n\n        const response = httpMocks.createResponse<Response>();\n\n        routeHandler(request, response);\n\n        // Assertions using common test patterns (e.g., Jest/Chai style)\n        expect(response.statusCode).toBe(200);\n        expect(response._isEndCalled()).toBe(true);\n        expect(response._isJSON()).toBe(true);\n        expect(response._getData()).toEqual(JSON.stringify({\n            name: 'Bob Dog',\n            age: 42,\n            email: 'bob@dog.com'\n        }));\n    });\n\n    it('should return 404 for an invalid ID', () => {\n        const request = httpMocks.createRequest<Request>({\n            method: 'GET',\n            url: '/user/99',\n            params: {\n                id: '99'\n            }\n        });\n\n        const response = httpMocks.createResponse<Response>();\n\n        routeHandler(request, response);\n\n        expect(response.statusCode).toBe(404);\n        expect(response._isEndCalled()).toBe(true);\n        expect(response._getData()).toEqual('User not found');\n    });\n});\n\n// Minimal Jest-like environment for standalone execution\nfunction describe(name: string, fn: () => void) {\n    console.log(`\n${name}`);\n    fn();\n}\nfunction it(name: string, fn: () => void) {\n    process.stdout.write(`  - ${name}...`);\n    try {\n        fn();\n        console.log(' ✅');\n    } catch (e: any) {\n        console.log(' ❌');\n        console.error(e.message);\n    }\n}\nconst expect = (value: any) => ({\n    toBe: (expected: any) => {\n        if (value !== expected) throw new Error(`Expected ${value} to be ${expected}`);\n    },\n    toEqual: (expected: any) => {\n        if (JSON.stringify(value) !== JSON.stringify(expected)) throw new Error(`Expected ${JSON.stringify(value)} to equal ${JSON.stringify(expected)}`);\n    }\n});","lang":"typescript","description":"This quickstart demonstrates how to unit test an Express-style route handler using `node-mocks-http` with TypeScript. It shows how to create mock request and response objects, pass them to a handler, and assert on the mocked response's state and data."},"warnings":[{"fix":"Install peer dependencies: `npm install --save-dev @types/node @types/express` or `yarn add --dev @types/node @types/express`.","message":"When using TypeScript, remember to install the necessary `@types` packages (e.g., `@types/express`, `@types/node`). Although `node-mocks-http` ships with its own types, these peer dependencies are crucial for correctly typing the underlying framework interfaces your code expects.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Pass a functional event emitter in `createResponse` options: `httpMocks.createResponse({ eventEmitter: require('events').EventEmitter })`.","message":"The mock `response` object's built-in event emitter is not fully functional and does not emit events by default. If your code under test relies on `response.on('event', ...)` for testing event handlers, you must provide your own event emitter instance to the mock response.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Specify the generic types: `httpMocks.createRequest<NextApiRequest>({...})` and `httpMocks.createResponse<NextApiResponse>()`. Remember to import `NextApiRequest` and `NextApiResponse` from `next`.","message":"When testing Next.js API routes or App Router handlers with TypeScript, ensure you import the specific `NextApiRequest`, `NextApiResponse`, `NextRequest`, or `NextResponse` types from the `next` package and use them as generics with `createRequest` and `createResponse`. By default, `node-mocks-http` mocks are Express-based.","severity":"gotcha","affected_versions":">=1.14.0"},{"fix":"If encountering issues with ESM and mocking, check your test runner's ESM configuration (e.g., `\"type\": \"module\"` in `package.json`). For advanced module-level mocking in ESM, consider libraries like `testdouble` or alternative test runners like `vitest` which have better ESM support.","message":"Node.js ESM (ECMAScript Modules) support in testing frameworks and mocking libraries can be complex. While `node-mocks-http` supports ESM imports for itself, mocking dependencies within ESM test files might require specific configurations or alternative tools like `testdouble` for module-level mocking.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure you import `httpMocks` as a default export (`import httpMocks from 'node-mocks-http';` for ESM or `const httpMocks = require('node-mocks-http');` for CJS) and then call its methods: `httpMocks.createRequest()`.","cause":"Attempting to destructure `createRequest` or `createResponse` directly from the package, or using CommonJS `require` in an ESM context (or vice-versa) incorrectly.","error":"TypeError: httpMocks.createRequest is not a function"},{"fix":"Add the correct generic type parameter to `createRequest` and `createResponse`, for example: `httpMocks.createRequest<express.Request>({...})` or `httpMocks.createResponse<express.Response>()`. Remember to import the `Request` and `Response` types from your framework (e.g., `import type { Request, Response } from 'express';`).","cause":"TypeScript error due to `createRequest` or `createResponse` being used without specifying the correct generic type, causing the mock object to default to `http.IncomingMessage` or `http.ServerResponse` which might not match the specific framework types (e.g., Express `Request`).","error":"TS2345: Argument of type '{}' is not assignable to parameter of type 'Request'. Property 'body' is missing in type '{}' but required in type 'Request'."},{"fix":"Ensure that your route handler has called a method like `response.send()` or `response.end()` to complete the response before attempting to retrieve data. Also, `_getJSONData()` specifically expects JSON content.","cause":"The `_getJSONData()` (and similar `_getData()`, `_getHeaders()` etc.) methods are non-standard helper methods added by `node-mocks-http` for testing purposes, which might be called before the response stream has ended or if the response content is not JSON.","error":"response._getJSONData is not a function"}],"ecosystem":"npm"}