1.14.1 • Published 4 months ago

node-mocks-http v1.14.1

Weekly downloads
222,581
License
MIT
Repository
github
Last release
4 months ago

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

or

$ yarn add node-mocks-http --dev

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. 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.
});

API

.createRequest()

httpMocks.createRequest(options)

Where options is an object hash with any of the following values:

optiondescriptiondefault value
methodrequest HTTP method'GET'
urlrequest URL''
originalUrlrequest original URLurl
baseUrlrequest base URLurl
pathrequest path''
paramsobject hash with params{}
sessionobject hash with session valuesundefined
cookiesobject hash with request cookies{}
socketobject hash with request socket{}
signedCookiesobject hash with signed cookiesundefined
headersobject hash with request headers{}
bodyobject hash with body{}
queryobject hash with query values{}
filesobject 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:

optiondescriptiondefault value
localsobject that contains response local variables{}
eventEmitterevent emitter used by response objectmockEventEmitter
writableStreamwritable stream used by response objectmockWritableStream
reqRequest object being responded tonull

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.

@withjoy/server-core-test@modern-js/plugin-ssger-prism-web@infinitebrahmanuniverse/nolb-node-macumen-academy-main-api-v2fusion-core@everything-registry/sub-chunk-2306@hasnat/http-stale-cache-proxy@mmdzov/pswd@neap/funcky@neap/funky@larner.dev/api@fusebit-int/frameworkdialogflow-fulfillment-v2-middlewaredigipolis-response@lilyrose2798/trpc-openapidelenitiest@metrik/trpc-openapistraingg_backendstream-uploadsstreaming-fusion-coresvelte-blitzssrframetrpc-swaggertrpc-openapitrpc-openapi-fetchtrpc-openapi-fork-fastify-pr-177webdev-infraxdn-routerwebsocket-mockupwebfunc@freeatnet/chai-passport-strategy@digipolis/responselivemock@shopify/jest-koa-mocks@shopify/koa-react-sidecar@slicknode/core@shuvi/platform-web@story-health/vitest-koa-mocks@usevenice/trpc-openapi@ubi2/adapter.http@pepperi-addons/cpi-node@webfunc/webfunc@rpcbase/bundler-server@notevenaneko/trpc-openapi@quoin/node-test-helpers-core@pubsweet/component-aws-s3@saegeullee/apollo-server-integration-testing@sebinsua/trpc-openapi@seagull/routes@iotakingdoms/auth@iotakingdoms/common@kevingorg/fusion-core@pablosz/apollo-server-integration-testing@potatohd/trpc-openapilananext-zod-router@zhouzi/apollo-server-integration-testingevaengine@toincrease/node-context@untool/expressmizarmizar-ssrframe@uvue/vue-cli-plugin-ssrmu-libmycro-util-policies@xysfe/blitz-server@xdn/router@duplojs/testingnext-page-testernext-page-tester-rewnewednext-test-api-routesnext-testing-librarynext-typed-connectnextdoornextonapi-nextexpress-boom-typescriptexpress-request-mockonedionys-cors-middlewareexpect-expressfascia@fisch0920/trpc-openapiexpress-react-middlewareexpress-repl-toolkitexpress-help-middlewareexpress-test-utilsfull-send-reporterfunctional-route-tester@alola-react/plugin-ssgpostgraphile-node@bolttech/frontend-session@alex8628/trpc-swagger@alessiocancian/trpc-openapi@alexmsmithca/fusion-corefusion-core-betafusion-test-utilshttp-stale-cache-proxyhops-rendererhops-express
1.14.1

4 months ago

1.14.0

4 months ago

1.13.0

8 months ago

1.12.2

1 year ago

1.12.1

1 year ago

1.11.0

3 years ago

1.10.1

3 years ago

1.10.0

3 years ago

1.9.0

4 years ago

1.8.1

4 years ago

1.8.0

5 years ago

1.7.6

5 years ago

1.7.5

5 years ago

1.7.4

5 years ago

1.7.3

6 years ago

1.7.2

6 years ago

1.7.1

6 years ago

1.7.0

6 years ago

1.5.8

6 years ago

1.6.7

6 years ago

1.6.6

7 years ago

1.6.5

7 years ago

1.6.4

7 years ago

1.6.3

7 years ago

1.6.2

7 years ago

1.6.1

7 years ago

1.5.6

7 years ago

1.5.5

7 years ago

1.5.4

8 years ago

1.5.3

8 years ago

1.5.2

8 years ago

1.5.1

8 years ago

1.5.0

8 years ago

1.4.4

9 years ago

1.4.3

9 years ago

1.4.2

9 years ago

1.4.1

9 years ago

1.4.0

9 years ago

1.3.0

9 years ago

1.2.7

9 years ago

1.2.6

9 years ago

1.2.5

9 years ago

1.2.4

9 years ago

1.2.3

9 years ago

1.2.2

9 years ago

1.2.1

10 years ago

1.2.0

10 years ago

1.1.0

10 years ago

1.0.4

10 years ago

1.0.3

10 years ago

1.0.1

11 years ago

1.0.0

11 years ago

0.0.9

11 years ago

0.0.8

12 years ago

0.0.7

12 years ago

0.0.6

12 years ago

0.0.5

12 years ago

0.0.4

12 years ago

0.0.2

12 years ago

0.0.1

12 years ago