GithubHelp home page GithubHelp logo

dorianblues / node-mocks-http Goto Github PK

View Code? Open in Web Editor NEW

This project forked from eugef/node-mocks-http

0.0 1.0 0.0 546 KB

Mock 'http' objects for testing Express routing functions

License: Other

JavaScript 100.00%

node-mocks-http's Introduction

node-mocks-http logo

NPM version Build Status Gitter chat

Mock 'http' objects for testing Express 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 --save-dev node-mocks-http

Our example includes --save-dev based on the assumption that node-mocks-http will be used as a development dependency..

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

var 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:

var 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) {

    var request  = httpMocks.createRequest({
        method: 'GET',
        url: '/user/42',
        params: {
          id: 42
        }
    });

    var response = httpMocks.createResponse();

    routeHandler(request, response);

    var 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();

};

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:

var httpMocks = require('node-mocks-http');
var 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:

var httpMocks = require('node-mocks-http');
var req = httpMocks.createRequest();
var 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){
    var 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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.