All Projects → davesag → mock-req-res

davesag / mock-req-res

Licence: MIT License
Extensible mock req / res objects for use in unit tests of Express controller and middleware functions.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to mock-req-res

chronosjs
JS Channels (Events / Commands / Reqest-Response / Courier) Mechanism
Stars: ✭ 35 (-10.26%)
Mutual labels:  request, response
izzyparser-ios
IzzyParser is an iOS library for serializing and deserializing JSON:API objects
Stars: ✭ 19 (-51.28%)
Mutual labels:  request, response
WaterPipe
URL routing framework, requests/responses handler, and HTTP client for PHP
Stars: ✭ 24 (-38.46%)
Mutual labels:  request, response
Examples
Examples of Mock Service Worker usage with various frameworks and libraries.
Stars: ✭ 163 (+317.95%)
Mutual labels:  request, response
http
Aplus Framework HTTP Library
Stars: ✭ 113 (+189.74%)
Mutual labels:  request, response
Interceptors
Low-level HTTP/HTTPS/XHR/fetch request interception library.
Stars: ✭ 100 (+156.41%)
Mutual labels:  mock, request
active endpoint
[ARCHIVE] 🔧 ActiveEndpoint is middleware for Rails application that collect and analize request and response per request for route endpoint. It works with minimum affecting to application response time.
Stars: ✭ 13 (-66.67%)
Mutual labels:  request, response
Kitura Net
Kitura networking
Stars: ✭ 98 (+151.28%)
Mutual labels:  request, response
net
A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package.
Stars: ✭ 16 (-58.97%)
Mutual labels:  request, response
fakey-json
This is a utility for mocking json data that pretends the api response data with JSON format.
Stars: ✭ 27 (-30.77%)
Mutual labels:  mock, response
Holen
Declarative fetch for React
Stars: ✭ 152 (+289.74%)
Mutual labels:  request, response
mswjs.io
Official website and documentation for the Mock Service Worker library.
Stars: ✭ 77 (+97.44%)
Mutual labels:  mock, request
Netclient Ios
Versatile HTTP Networking in Swift
Stars: ✭ 117 (+200%)
Mutual labels:  request, response
reqres
Powerful classes for http requests and responses
Stars: ✭ 36 (-7.69%)
Mutual labels:  request, response
Alamofire
Elegant HTTP Networking in Swift
Stars: ✭ 36,896 (+94505.13%)
Mutual labels:  request, response
main
Mocks Server monorepo
Stars: ✭ 109 (+179.49%)
Mutual labels:  mock, expressjs
Alagarr
🦍 Alagarr is a request-response helper library that removes the boilerplate from your Node.js (AWS Lambda) serverless functions and helps make your code portable.
Stars: ✭ 58 (+48.72%)
Mutual labels:  request, response
Aura.http
HTTP Request and Response tools
Stars: ✭ 69 (+76.92%)
Mutual labels:  request, response
HttpUtility
HttpUtility is an open source MIT license project which is helpful in making HTTP requests and returns a decoded object from server. Right now this utility only parses JSON.
Stars: ✭ 28 (-28.21%)
Mutual labels:  request, response
servie
Standard, framework-agnostic HTTP interfaces for JavaScript servers and clients
Stars: ✭ 39 (+0%)
Mutual labels:  request, response

mock-req-res

Extensible mock req / res objects for use in unit tests of ExpressJS controller and middleware functions.

NPM

Prerequisites

This library assumes:

  1. You are using NodeJS 8+
  2. You write properly isolated unit tests of route controllers and ExpressJS middleware functions
  3. You use sinon version 5 or better.

Install

Add mock-req-res as a devDependency:

npm i -D mock-req-res

If you are using TypeScript you can add @types/mock-req-res:

npm i -D @types/mock-req-res

Mocking req.

To test a controller or middleware function you need to mock a request object.

Do this with:

const req = mockRequest(options)

The options can be anything you wish to attach or override in the request.

The vanilla mockRequest gives you the following properties, as well as functions in the form of sinon stubs.

app: {},
baseUrl: '',
body: {},
cookies: {},
fresh: true,
headers: {},
hostname: '',
ip: '127.0.0.1',
ips: [],
method: 'GET',
originalUrl: '',
params: {},
path: '',
protocol: 'https',
query: {},
route: {},
secure: true,
signedCookies: {},
stale: false,
subdomains: [],
xhr: true,
accepts: stub(),
acceptsCharsets: stub(),
acceptsEncodings: stub(),
acceptsLanguages: stub(),
get: stub(),
is: stub(),
range: stub(),

Mocking res.

To test a route controller or middleware function you also need to mock a response object.

Do this with:

const res = mockResponse(options)

The options can be anything you wish to attach or override in the request.

The vanilla mockResponse gives you the following functions, in the form of sinon spies and stubs.

app: {},
headersSent: false,
locals: {},
append: spy(),
attachment: spy(),
clearCookie: spy(),
download: spy(),
end: spy(),
format: spy(),
json: spy(),
jsonp: spy(),
links: spy(),
location: spy(),
redirect: spy(),
render: spy(),
send: spy(),
sendFile: spy(),
sendStatus: spy(),
set: spy(),
setHeader: spy(),
type: spy(),
get: stub(),
getHeader: stub(),
cookie: stub().returns(res), // returns itself, allowing chaining
status: stub().returns(res), // returns itself, allowing chaining
vary: stub().returns(res) // returns itself, allowing chaining

Note you can always add other spies or stubs as needed via the options.

Example

Let's say you have a route controller like this:

const save = require('../../utils/saveThing') // assume this exists.

const createThing = async (req, res) => {
  const { name, description } = req.body
  if (!name || !description) throw new Error('Invalid Properties')
  const saved = await save({ name, description })
  res.json(saved)
}

To unit test this you could use Mocha, Chai, Sinon, and Proxyquire as follows:

const { expect } = require('chai')
const { stub, match } = require('sinon')
const { mockRequest, mockResponse } = require('mock-req-res')
const proxyquire = require('proxyquire')

describe('src/api/things/createThing', () => {
  const mockSave = stub()

  const createThing = proxyquire('../../src/api/things/createThing', {
    '../../utils/saveThing': mockSave
  })

  const res = mockResponse()

  const resetStubs = () => {
    mockSave.resetHistory()
    res.json.resetHistory()
  }

  context('happy path', () => {
    const name = 'some name'
    const description = 'some description'

    const req = mockRequest({ body: { name, description } })
    const expected = { name, description, id: 1 }
    before(async () => {
      save.returns(expected)
      await createThing(req, res)
    })

    after(resetStubs)

    it('called save with the right data', () => {
      expect(save).to.have.been.calledWith(match({ name, description }))
    })

    it('called res.json with the right data', () => {
      expect(res.json).to.have.been.calledWith(match(expected))
    })
  })

  // and also test the various unhappy path scenarios.
})

See also

Development

Branches

Branch Status Coverage Audit Notes
develop CircleCI codecov Vulnerabilities Work in progress
main CircleCI codecov Vulnerabilities Latest stable release

Prerequisites

  • NodeJS. I use nvm to manage Node versions — brew install nvm.

Test it

  • npm test — runs the unit tests.
  • npm run test:unit:cov — runs the unit tests with code coverage

Lint it

npm run lint

Contributing

Please see the contributing notes.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].