npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

node-mocks-http

v1.16.2

Published

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

Downloads

6,011,722

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('[email protected]', 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('[email protected]', 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.