Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

node-mocks-http

eugef3.7mMIT1.16.2TypeScript support: included

Mock 'http' objects for testing Express, Next.js and Koa routing functions

mock, stub, dummy, nodejs, js, testing, test, http, http mock

readme

Logo


NPM version

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.

Installation

This project is available as a NPM package.

$ npm install node-mocks-http --save-dev
$ npm install @types/node @types/express --save-dev # when using TypeScript

or

$ yarn add node-mocks-http --dev
$ yarn add @types/node @types/express --dev # when using TypeScript

After installing the package include the following in your test files:

const httpMocks = require('node-mocks-http');

Usage

Suppose you have the following Express route:

app.get('/user/:id', routeHandler);

And you have created a function to handle that route's call:

const routeHandler = function( request, response ) { ... };

You can easily test the routeHandler function with some code like this using the testing framework of your choice:

exports['routeHandler - Simple testing'] = function (test) {
    const request = httpMocks.createRequest({
        method: 'GET',
        url: '/user/42',
        params: {
            id: 42
        }
    });

    const response = httpMocks.createResponse();

    routeHandler(request, response);

    const data = response._getJSONData(); // short-hand for JSON.parse( response._getData() );
    test.equal('Bob Dog', data.name);
    test.equal(42, data.age);
    test.equal('bob@dog.com', data.email);

    test.equal(200, response.statusCode);
    test.ok(response._isEndCalled());
    test.ok(response._isJSON());
    test.ok(response._isUTF8());

    test.done();
};

TypeScript typings

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:

it('should handle expressjs requests', () => {
    const mockExpressRequest = httpMocks.createRequest({
        method: 'GET',
        url: '/user/42',
        params: {
            id: 42
        }
    });
    const mockExpressResponse = httpMocks.createResponse();

    routeHandler(request, response);

    const data = response._getJSONData();
    test.equal('Bob Dog', data.name);
    test.equal(42, data.age);
    test.equal('bob@dog.com', data.email);

    test.equal(200, response.statusCode);
    test.ok(response._isEndCalled());
    test.ok(response._isJSON());
    test.ok(response._isUTF8());

    test.done();
});

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:

it('should handle nextjs requests', () => {
    const mockExpressRequest = httpMocks.createRequest<NextApiRequest>({
        method: 'GET',
        url: '/user/42',
        params: {
            id: 42
        }
    });
    const mockExpressResponse = httpMocks.createResponse<NextApiResponse>();

    // ... the rest of the test as above.
});

It is also possible to mock requests from the NextJS new AppRouter:

it('should handle nextjs app reouter requests', () => {
    const mockExpressRequest = httpMocks.createRequest<NextRequest>({
        method: 'GET',
        url: '/user/42',
        params: {
            id: 42
        }
    });
    const mockExpressResponse = httpMocks.createResponse<NextResponse>();

    // ... the rest of the test as above.
});

API

.createRequest()

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.

.createResponse()

httpMocks.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:

const httpMocks = require('node-mocks-http');
const res = httpMocks.createResponse({
  eventEmitter: require('events').EventEmitter
});

// ...
  it('should do something', function(done) {
    res.on('end', function() {
      assert.equal(...);
      done();
    });
  });
// ...

This is an example to send request body and trigger it's 'data' and 'end' events:

const httpMocks = require('node-mocks-http');
const req = httpMocks.createRequest();
const res = httpMocks.createResponse({
    eventEmitter: require('events').EventEmitter
});

// ...
it('should do something', function (done) {
    res.on('end', function () {
        expect(response._getData()).to.equal('data sent in request');
        done();
    });

    route(req, res);

    req.send('data sent in request');
});

function route(req, res) {
    let data = [];
    req.on('data', (chunk) => {
        data.push(chunk);
    });
    req.on('end', () => {
        data = Buffer.concat(data);
        res.write(data);
        res.end();
    });
}
// ...

.createMocks()

httpMocks.createMocks(reqOptions, resOptions);

Merges createRequest and createResponse. Passes given options object to each constructor. Returns an object with properties req and res.

Design Decisions

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.

For Developers

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.

Release Notes

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.

License

Licensed under MIT.

changelog

v 1.16.2

v 1.16.1

v 1.16.0

  • Add appendHeader to MockResponse Issue #306.
  • Add Fetch API types as accepted mock parameters Issue #291.

v 1.15.1

v 1.15.0

  • Add to write() and end() support of TypedArray Issue #300.
  • Fix: return empty string when send() was called with undefined Issue #298.

v 1.14.1

  • Move express and node types to prod deps Issue #290.

v 1.14.0

v 1.13.0

v 1.12.2

v 1.12.1

  • Fix lint issue

v 1.12.0

  • Make it easier to create mocks for the node http library Issue #259.
  • mockResponse.end(): added callback triggering once end() logic has run Issue #248.

v 1.11.0

  • Fix request.ip and add request.ips Issue #244.
  • Add response.attachment() from express Issue #246.
  • Add request.getHeader() alias for request.header() Issue #241.

v 1.10.1

v 1.10.0

v 1.9.0

  • Implement response.getHeaderNames() and response.hasHeader() Issue #222.
  • Remove calls to deprecated Buffer constructors Issue #221.
  • Run tests for Node 10, 12 and 14. Drop support for Node 6 and 8 Issue #218.
  • Implement response.getHeaders() Issue #217.
  • Add req.subdomains Issue #213.
  • Add socket option to mockRequest Issue #209.
  • Fix index.d.ts Issue #205.
  • Added support for response.writableEnded and response.writableFinished Issue #205.

v 1.8.1

  • Enable res.render() callback argument Issue #197.

v 1.8.0

v 1.7.6

v 1.7.5

  • Updated the dependency tree with newer versions of eslint.

v 1.7.4

  • Added _getJSONData function with data sent to the user as JSON. #181

v 1.7.3

  • Added .range() on a mocked request mimicking the same function on Express' request. #175

v 1.7.2

  • Revert Turn mock request into a stream #174
  • Fix security issues reported by npm audit

v 1.7.1

  • Turn mock request into a stream #169
  • Added missing typings for "locals" & create a helper method to get locals #170
  • Make header names case-insensitive in response #172
  • Throw an error object instead of a string #173

v 1.7.0

  • Add support for Buffer payload #154
  • Send request body/payload to trigger relevant events #164

v 1.6.8

  • Better typings, including the following (see PR #158 for details):
    • request object for a controller fn which is typed as extension of express.Request
    • same for Response
    • custom properties appended to request object
    • fixed missing _getRenderView method on Response

Note: As of this release, we are officially supporting:

  • 6.13
  • 8.9
  • 9.6

v 1.6.7

  • Set an expiration date to a cookie when deleting it #155
  • No finish event, end event called when it shouldn't be. #112
  • Add support for append on MockResponse #143
  • Add locals object to response #135

Special shoutout to Eugene Fidelin for joining the team and helping out so much.

v 1.6.6

v 1.6.5

  • Query type definition now more flexible PR #146

v 1.6.4

  • Incorporated a trimmed down published NPM artifact PR #141

v 1.6.3

  • Moved @types/express to dev-dependencies. PR #136

v 1.6.1

  • Fix for Issue #130 for method chaining for cookie() and clearCookie()
  • Fix for Issue #131 for adding finished to the response

v 1.6.0

  • Dropping support for Node's "0" version, but will continue to support v4.
  • Verifying our builds with v6 (latest stable) as well as current work (v7)
  • Removing dependency on lodash and other bug fixes

v 1.5.4

  • Call write method from json method of responseMock PR #98

v 1.5.3

  • Add .format to the mockResponse object PR #94
  • Add .location to the mockResponse object PR #96
  • Add API method, createMocks to create both mocks with correct references

v 1.5.2

  • Add case insensitive response headers #85
  • Fix behavior of mockResponse.writeHead #92
  • Add support for statusMessage #84
  • Fix issue with req.param not returning when false #82
  • Other bug fixes

v 1.5.1

  • Add support for the .vary() response method

v 1.5.0

Documentation changes, a new feature, and better behaviors, including:

  • Added jsonp method that takes a status code and a payload, see PR #79
  • Now able to attach non-standard properties to the mock request object. PR #74
  • param now takes a default value, see PR #76
  • Emit end when redirecting, see PR #77
  • Documentation changes, see PR #64, PR #75, PR #78

v 1.4.4

Bug fix release, including the following:

  • Fixed for #67
  • Merge fix for #68
  • Merge fix for #70
  • Merge fix for #73

v 1.2.0

  • Adds a .header and .get method to the request.

v 1.1.0

  • Adds a .header, .set, and .get method to the response.

v 1.0.4

  • Adds the MIT license

v 1.0.3

  • Merged changes by invernizzie: to address #11

  • Merged changes by ericchaves:

    I extended your library a little but so it could also handle some structured responses. By doing so res.send now evaluate the data passed and search for either a statusCode or httpCode to be used, and also for a body to send as _data.

    It still working as expected (at least tests passed) for regular HTTP responses.

    Although I did it with node-restify in mind, it should work well for all other libs.

v 1.0.2

  • Adds a .json() method to the response. (Thanks, diachedelic)
  • Cleaned up all source files so ./run-tests passes.
  • Cleaned up jshint issues.

v 1.0.1

  • Adds support for response redirect and render

v 0.0.9

  • Adds support for response cookies

v 0.0.8

  • Adds support for request headers
  • Fix wrong function name of set cookies

v 0.0.7

  • Adds support for request cookies

v 0.0.6

  • Adds support for request files

v 0.0.5

  • Fixed a bug where response.send() can take two parameters, the status code and the data to send.

v 0.0.4

  • Adds a request.session that can be set during construction (or via calling the _setSessionVariable() method, and read as an object.

v 0.0.3

  • Adds a request.query that can be set during construction and read as an object.

v 0.0.2

  • Code refactoring of the Response mock.

v 0.0.1

  • Initial code banged out one late night...