{"id":13456306,"url":"https://github.com/eugef/node-mocks-http","last_synced_at":"2025-04-25T14:47:35.388Z","repository":{"id":2502025,"uuid":"3476812","full_name":"eugef/node-mocks-http","owner":"eugef","description":"Mock 'http' objects for testing Express,js, Next.js and Koa routing functions","archived":false,"fork":false,"pushed_at":"2024-12-10T11:05:50.000Z","size":1293,"stargazers_count":769,"open_issues_count":1,"forks_count":135,"subscribers_count":18,"default_branch":"master","last_synced_at":"2025-04-22T14:04:50.866Z","etag":null,"topics":["expressjs","nextjs","nodejs","testing"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/eugef.png","metadata":{"files":{"readme":"README.md","changelog":"HISTORY.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2012-02-18T07:18:07.000Z","updated_at":"2025-04-01T12:34:56.000Z","dependencies_parsed_at":"2023-12-11T17:45:39.833Z","dependency_job_id":"25b7de88-3b3d-49af-aec7-0202f4288942","html_url":"https://github.com/eugef/node-mocks-http","commit_stats":{"total_commits":415,"total_committers":97,"mean_commits":4.278350515463917,"dds":0.6795180722891566,"last_synced_commit":"72979848f3008bc61dfcc131956b63713694e69a"},"previous_names":["howardabrams/node-mocks-http"],"tags_count":38,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eugef%2Fnode-mocks-http","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eugef%2Fnode-mocks-http/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eugef%2Fnode-mocks-http/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eugef%2Fnode-mocks-http/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eugef","download_url":"https://codeload.github.com/eugef/node-mocks-http/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250522299,"owners_count":21444511,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["expressjs","nextjs","nodejs","testing"],"created_at":"2024-07-31T08:01:19.586Z","updated_at":"2025-04-24T04:21:44.429Z","avatar_url":"https://github.com/eugef.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"[![Logo](https://user-images.githubusercontent.com/895071/227720269-37e34019-eba0-4768-80ab-1a4dad043043.png)](https://github.com/eugef/node-mocks-http)\n\n---\n\n[![NPM version][npm-badge]][npm-url]\n\nMock 'http' objects for testing [Express][express-url], [Next.js][nextjs-url] and [Koa][koa-url] routing functions,\nbut could be used for testing any [Node.js][node-url] web server applications that have code that requires mockups of the `request` and `response` objects.\n\n## Installation\n\nThis project is available as a\n[NPM package][npm-url].\n\n```bash\n$ npm install node-mocks-http --save-dev\n$ npm install @types/node @types/express --save-dev # when using TypeScript\n```\n\nor\n\n```bash\n$ yarn add node-mocks-http --dev\n$ yarn add @types/node @types/express --dev # when using TypeScript\n```\n\nAfter installing the package include the following in your test files:\n\n```js\nconst httpMocks = require('node-mocks-http');\n```\n\n## Usage\n\nSuppose you have the following Express route:\n\n```js\napp.get('/user/:id', routeHandler);\n```\n\nAnd you have created a function to handle that route's call:\n\n```js\nconst routeHandler = function( request, response ) { ... };\n```\n\nYou can easily test the `routeHandler` function with some code like\nthis using the testing framework of your choice:\n\n```js\nexports['routeHandler - Simple testing'] = function (test) {\n    const request = httpMocks.createRequest({\n        method: 'GET',\n        url: '/user/42',\n        params: {\n            id: 42\n        }\n    });\n\n    const response = httpMocks.createResponse();\n\n    routeHandler(request, response);\n\n    const data = response._getJSONData(); // short-hand for JSON.parse( response._getData() );\n    test.equal('Bob Dog', data.name);\n    test.equal(42, data.age);\n    test.equal('bob@dog.com', data.email);\n\n    test.equal(200, response.statusCode);\n    test.ok(response._isEndCalled());\n    test.ok(response._isJSON());\n    test.ok(response._isUTF8());\n\n    test.done();\n};\n```\n\n### TypeScript typings\n\nThe typings for TypeScript are bundled with this project. In particular, the `.createRequest()`, `.createResponse()` and `.createMocks()` methods are typed and are generic. Unless specified explicitly, they will be return an Express-based request/response object:\n\n```ts\nit('should handle expressjs requests', () =\u003e {\n    const mockExpressRequest = httpMocks.createRequest({\n        method: 'GET',\n        url: '/user/42',\n        params: {\n            id: 42\n        }\n    });\n    const mockExpressResponse = httpMocks.createResponse();\n\n    routeHandler(request, response);\n\n    const data = response._getJSONData();\n    test.equal('Bob Dog', data.name);\n    test.equal(42, data.age);\n    test.equal('bob@dog.com', data.email);\n\n    test.equal(200, response.statusCode);\n    test.ok(response._isEndCalled());\n    test.ok(response._isJSON());\n    test.ok(response._isUTF8());\n\n    test.done();\n});\n```\n\nThe expected type parameter in the mock request and response expects any type that extends the NodeJS\n`http.IncomingRequest` interface or Fetch API `Request` class. This means you can also mock requests\ncoming from other frameworks too. An example for NextJS request will look like this:\n\n```ts\nit('should handle nextjs requests', () =\u003e {\n    const mockExpressRequest = httpMocks.createRequest\u003cNextApiRequest\u003e({\n        method: 'GET',\n        url: '/user/42',\n        params: {\n            id: 42\n        }\n    });\n    const mockExpressResponse = httpMocks.createResponse\u003cNextApiResponse\u003e();\n\n    // ... the rest of the test as above.\n});\n```\n\nIt is also possible to mock requests from the NextJS new AppRouter:\n\n```ts\nit('should handle nextjs app reouter requests', () =\u003e {\n    const mockExpressRequest = httpMocks.createRequest\u003cNextRequest\u003e({\n        method: 'GET',\n        url: '/user/42',\n        params: {\n            id: 42\n        }\n    });\n    const mockExpressResponse = httpMocks.createResponse\u003cNextResponse\u003e();\n\n    // ... the rest of the test as above.\n});\n```\n\n## API\n\n### .createRequest()\n\n```\nhttpMocks.createRequest(options)\n```\n\nWhere options is an object hash with any of the following values:\n\n| option          | description                      | default value |\n| --------------- | -------------------------------- | ------------- |\n| `method`        | request HTTP method              | 'GET'         |\n| `url`           | request URL                      | ''            |\n| `originalUrl`   | request original URL             | `url`         |\n| `baseUrl`       | request base URL                 | `url`         |\n| `path`          | request path                     | ''            |\n| `params`        | object hash with params          | {}            |\n| `session`       | object hash with session values  | `undefined`   |\n| `cookies`       | object hash with request cookies | {}            |\n| `socket`        | object hash with request socket  | {}            |\n| `signedCookies` | object hash with signed cookies  | `undefined`   |\n| `headers`       | object hash with request headers | {}            |\n| `body`          | object hash with body            | {}            |\n| `query`         | object hash with query values    | {}            |\n| `files`         | object hash with values          | {}            |\n\nThe object returned from this function also supports the [Express request](http://expressjs.com/en/4x/api.html#req) functions ([`.accepts()`](http://expressjs.com/en/4x/api.html#req.accepts), [`.is()`](http://expressjs.com/en/4x/api.html#req.is), [`.get()`](http://expressjs.com/en/4x/api.html#req.get), [`.range()`](http://expressjs.com/en/4x/api.html#req.range), etc.). Please send a PR for any missing functions.\n\n### .createResponse()\n\n```js\nhttpMocks.createResponse(options);\n```\n\nWhere options is an object hash with any of the following values:\n\n| option           | description                                     | default value        |\n| ---------------- | ----------------------------------------------- | -------------------- |\n| `locals`         | object that contains `response` local variables | `{}`                 |\n| `eventEmitter`   | event emitter used by `response` object         | `mockEventEmitter`   |\n| `writableStream` | writable stream used by `response` object       | `mockWritableStream` |\n| `req`            | Request object being responded to               | null                 |\n\n\u003e NOTE: The out-of-the-box mock event emitter included with `node-mocks-http` is\n\u003e not a functional event emitter and as such does not actually emit events. If you\n\u003e wish to test your event handlers you will need to bring your own event emitter.\n\n\u003e Here's an example:\n\n```js\nconst httpMocks = require('node-mocks-http');\nconst res = httpMocks.createResponse({\n  eventEmitter: require('events').EventEmitter\n});\n\n// ...\n  it('should do something', function(done) {\n    res.on('end', function() {\n      assert.equal(...);\n      done();\n    });\n  });\n// ...\n```\n\n\u003e This is an example to send request body and trigger it's 'data' and 'end' events:\n\n```js\nconst httpMocks = require('node-mocks-http');\nconst req = httpMocks.createRequest();\nconst res = httpMocks.createResponse({\n    eventEmitter: require('events').EventEmitter\n});\n\n// ...\nit('should do something', function (done) {\n    res.on('end', function () {\n        expect(response._getData()).to.equal('data sent in request');\n        done();\n    });\n\n    route(req, res);\n\n    req.send('data sent in request');\n});\n\nfunction route(req, res) {\n    let data = [];\n    req.on('data', (chunk) =\u003e {\n        data.push(chunk);\n    });\n    req.on('end', () =\u003e {\n        data = Buffer.concat(data);\n        res.write(data);\n        res.end();\n    });\n}\n// ...\n```\n\n### .createMocks()\n\n```js\nhttpMocks.createMocks(reqOptions, resOptions);\n```\n\nMerges `createRequest` and `createResponse`. Passes given options object to each\nconstructor. Returns an object with properties `req` and `res`.\n\n## Design Decisions\n\nWe wanted some simple mocks without a large framework.\n\nWe also wanted the mocks to act like the original framework being\nmocked, but allow for setting of values before calling and inspecting\nof values after calling.\n\n## For Developers\n\nWe are looking for more volunteers to bring value to this project,\nincluding the creation of more objects from the\n[HTTP module][node-http-module-url].\n\nThis project doesn't address all features that must be\nmocked, but it is a good start. Feel free to send pull requests,\nand a member of the team will be timely in merging them.\n\nIf you wish to contribute please read our [Contributing Guidelines](CONTRIBUTING.md).\n\n## Release Notes\n\nMost releases fix bugs with our mocks or add features similar to the\nactual `Request` and `Response` objects offered by Node.js and extended\nby Express.\n\nSee the [Release History](HISTORY.md) for details.\n\n[release-notes]: https://github.com/eugef/node-mocks-http/releases\n\n## License\n\nLicensed under [MIT](LICENSE).\n\n[npm-badge]: https://badge.fury.io/js/node-mocks-http.png\n[npm-url]: https://www.npmjs.com/package/node-mocks-http\n[express-url]: https://expressjs.com\n[nextjs-url]: https://nextjs.org\n[koa-url]: https://koajs.com\n[node-url]: http://www.nodejs.org\n[node-http-module-url]: http://nodejs.org/docs/latest/api/http.html\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feugef%2Fnode-mocks-http","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Feugef%2Fnode-mocks-http","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feugef%2Fnode-mocks-http/lists"}