{"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.","language":"javascript","status":"active","last_verified":"Tue Apr 21","install":{"commands":["npm install node-mocks-http"],"cli":null},"imports":["import httpMocks from 'node-mocks-http';","const httpMocks = require('node-mocks-http');","import httpMocks from 'node-mocks-http';\nconst request = httpMocks.createRequest();","import type { NextApiRequest, NextApiResponse } from 'next';\nimport httpMocks from 'node-mocks-http';\n\nconst mockRequest = httpMocks.createRequest<NextApiRequest>({});"],"auth":{"required":false,"env_vars":[]},"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.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}