Gathering detailed insights and metrics for node-mocks-http
Gathering detailed insights and metrics for node-mocks-http
Gathering detailed insights and metrics for node-mocks-http
Gathering detailed insights and metrics for node-mocks-http
node-mocks-http-self
Mock 'http' objects for testing Express routing functions
http-request-mock
Intercept & mock http requests issued by XMLHttpRequest, fetch, nodejs https/http module, axios, jquery, superagent, ky, node-fetch, request, got or any other request libraries by intercepting XMLHttpRequest, fetch and nodejs native requests in low level.
@cantremember/node-mocks-http
Mock 'http' objects for testing Express routing functions
@nunofgs/http-request-mock
Intercept & mock http requests issued by XMLHttpRequest, fetch, nodejs https/http module, axios, jquery, superagent, ky, node-fetch, request, got or any other request libraries by intercepting XMLHttpRequest, fetch and nodejs native requests in low level.
Mock 'http' objects for testing Express,js, Next.js and Koa routing functions
npm install node-mocks-http
Typescript
Module System
Min. Node Version
Node Version
NPM Version
96
Supply Chain
97.9
Quality
84.5
Maintenance
100
Vulnerability
100
License
JavaScript (73.19%)
TypeScript (26.78%)
Shell (0.03%)
Total Downloads
122,298,198
Last Day
112,738
Last Week
1,292,892
Last Month
5,655,598
Last Year
46,674,019
764 Stars
517 Commits
134 Forks
18 Watching
15 Branches
77 Contributors
Latest Version
1.16.2
Package Id
node-mocks-http@1.16.2
Unpacked Size
78.24 kB
Size
19.79 kB
File Count
17
NPM Version
10.5.0
Node Version
20.12.2
Publised On
10 Dec 2024
Cumulative downloads
Total Downloads
Last day
-52.4%
112,738
Compared to previous day
Last week
-3.3%
1,292,892
Compared to previous week
Last month
1.2%
5,655,598
Compared to previous month
Last year
66.1%
46,674,019
Compared to previous year
10
2
Mock 'http' objects for testing Express, Next.js and Koa routing functions,
but could be used for testing any Node.js web server applications that have code that requires mockups of the request
and response
objects.
This project is available as a NPM package.
1$ npm install node-mocks-http --save-dev 2$ npm install @types/node @types/express --save-dev # when using TypeScript
or
1$ yarn add node-mocks-http --dev 2$ yarn add @types/node @types/express --dev # when using TypeScript
After installing the package include the following in your test files:
1const httpMocks = require('node-mocks-http');
Suppose you have the following Express route:
1app.get('/user/:id', routeHandler);
And you have created a function to handle that route's call:
1const routeHandler = function( request, response ) { ... };
You can easily test the routeHandler
function with some code like
this using the testing framework of your choice:
1exports['routeHandler - Simple testing'] = function (test) { 2 const request = httpMocks.createRequest({ 3 method: 'GET', 4 url: '/user/42', 5 params: { 6 id: 42 7 } 8 }); 9 10 const response = httpMocks.createResponse(); 11 12 routeHandler(request, response); 13 14 const data = response._getJSONData(); // short-hand for JSON.parse( response._getData() ); 15 test.equal('Bob Dog', data.name); 16 test.equal(42, data.age); 17 test.equal('bob@dog.com', data.email); 18 19 test.equal(200, response.statusCode); 20 test.ok(response._isEndCalled()); 21 test.ok(response._isJSON()); 22 test.ok(response._isUTF8()); 23 24 test.done(); 25};
The 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:
1it('should handle expressjs requests', () => { 2 const mockExpressRequest = httpMocks.createRequest({ 3 method: 'GET', 4 url: '/user/42', 5 params: { 6 id: 42 7 } 8 }); 9 const mockExpressResponse = httpMocks.createResponse(); 10 11 routeHandler(request, response); 12 13 const data = response._getJSONData(); 14 test.equal('Bob Dog', data.name); 15 test.equal(42, data.age); 16 test.equal('bob@dog.com', data.email); 17 18 test.equal(200, response.statusCode); 19 test.ok(response._isEndCalled()); 20 test.ok(response._isJSON()); 21 test.ok(response._isUTF8()); 22 23 test.done(); 24});
The expected type parameter in the mock request and response expects any type that extends the NodeJS
http.IncomingRequest
interface or Fetch API Request
class. This means you can also mock requests
coming from other frameworks too. An example for NextJS request will look like this:
1it('should handle nextjs requests', () => { 2 const mockExpressRequest = httpMocks.createRequest<NextApiRequest>({ 3 method: 'GET', 4 url: '/user/42', 5 params: { 6 id: 42 7 } 8 }); 9 const mockExpressResponse = httpMocks.createResponse<NextApiResponse>(); 10 11 // ... the rest of the test as above. 12});
It is also possible to mock requests from the NextJS new AppRouter:
1it('should handle nextjs app reouter requests', () => { 2 const mockExpressRequest = httpMocks.createRequest<NextRequest>({ 3 method: 'GET', 4 url: '/user/42', 5 params: { 6 id: 42 7 } 8 }); 9 const mockExpressResponse = httpMocks.createResponse<NextResponse>(); 10 11 // ... the rest of the test as above. 12});
httpMocks.createRequest(options)
Where options is an object hash with any of the following values:
option | description | default value |
---|---|---|
method | request HTTP method | 'GET' |
url | request URL | '' |
originalUrl | request original URL | url |
baseUrl | request base URL | url |
path | request path | '' |
params | object hash with params | {} |
session | object hash with session values | undefined |
cookies | object hash with request cookies | {} |
socket | object hash with request socket | {} |
signedCookies | object hash with signed cookies | undefined |
headers | object hash with request headers | {} |
body | object hash with body | {} |
query | object hash with query values | {} |
files | object hash with values | {} |
The object returned from this function also supports the Express request functions (.accepts()
, .is()
, .get()
, .range()
, etc.). Please send a PR for any missing functions.
1httpMocks.createResponse(options);
Where options is an object hash with any of the following values:
option | description | default value |
---|---|---|
locals | object that contains response local variables | {} |
eventEmitter | event emitter used by response object | mockEventEmitter |
writableStream | writable stream used by response object | mockWritableStream |
req | Request object being responded to | null |
NOTE: The out-of-the-box mock event emitter included with
node-mocks-http
is not a functional event emitter and as such does not actually emit events. If you wish to test your event handlers you will need to bring your own event emitter.
Here's an example:
1const httpMocks = require('node-mocks-http'); 2const res = httpMocks.createResponse({ 3 eventEmitter: require('events').EventEmitter 4}); 5 6// ... 7 it('should do something', function(done) { 8 res.on('end', function() { 9 assert.equal(...); 10 done(); 11 }); 12 }); 13// ...
This is an example to send request body and trigger it's 'data' and 'end' events:
1const httpMocks = require('node-mocks-http'); 2const req = httpMocks.createRequest(); 3const res = httpMocks.createResponse({ 4 eventEmitter: require('events').EventEmitter 5}); 6 7// ... 8it('should do something', function (done) { 9 res.on('end', function () { 10 expect(response._getData()).to.equal('data sent in request'); 11 done(); 12 }); 13 14 route(req, res); 15 16 req.send('data sent in request'); 17}); 18 19function route(req, res) { 20 let data = []; 21 req.on('data', (chunk) => { 22 data.push(chunk); 23 }); 24 req.on('end', () => { 25 data = Buffer.concat(data); 26 res.write(data); 27 res.end(); 28 }); 29} 30// ...
1httpMocks.createMocks(reqOptions, resOptions);
Merges createRequest
and createResponse
. Passes given options object to each
constructor. Returns an object with properties req
and res
.
We wanted some simple mocks without a large framework.
We also wanted the mocks to act like the original framework being mocked, but allow for setting of values before calling and inspecting of values after calling.
We are looking for more volunteers to bring value to this project, including the creation of more objects from the HTTP module.
This project doesn't address all features that must be mocked, but it is a good start. Feel free to send pull requests, and a member of the team will be timely in merging them.
If you wish to contribute please read our Contributing Guidelines.
Most releases fix bugs with our mocks or add features similar to the
actual Request
and Response
objects offered by Node.js and extended
by Express.
See the Release History for details.
Licensed under MIT.
No vulnerabilities found.
No security vulnerabilities found.