README
Express Request Mock
A convenient wrapper for node-mocks-http which makes testing Express controllers and middleware easy.
const expressRequestMock = require('express-request-mock')
const subject = require('../../controllers/animals')
it('returns a 200 response', async () => {
const { res } = await expressRequestMock(subject, options)
expect(res.statusCode).to.equal(200)
})
Installation
This is a Node.js module available through the npm registry. Before installing, download and install Node.js. Node.js 12 or higher is required.
Installation is done using the npm install command:
$ npm install -D express-request-mock
Usage
First include the module in your test:
const expressRequestMock = require('express-request-mock')
The module provides one function which accepts up to three arguments:
- The route handler to test (a function which accepts a request, response, and optional fallthrough function.)
- An optional options object for
createRequest
(the options for which are documented here.) - An optional object with properties to append to the request and response objects (which can be useful when mocking middleware.)
const subject = require('../../controllers/animals')
const options = { query: { species: 'dog' } }
const decorators = { authorized: true }
const request = expressRequestMock(subject, options, decorators)
The function returns a promise which will resolve either when the response is ended or the fallthrough function (next()
) is called. The promise will reject if either the underlying code throws an error or the fallthrough function is called with an error.
The promise will resolve to an object with the following keys:
req
: The request object created bycreateRequest
res
: The response object created bycreateResponse
request.then(({ req, res }) => {
// write assertions!
})
Example
Below is an example using express-request-mock
to test a controller along with Mocha and Chai (but it also works just as well with Jest, Tap, or Jasmine!):
const { expect } = require('chai')
const expressRequestMock = require('express-request-mock')
const subject = require('../../controllers/animals')
describe('Controllers - Animals', () => {
context('when a valid species is requested', () => {
const options = { query: { species: 'dog' } }
it('returns a 200 response', async () => {
const { res } = await expressRequestMock(subject, options)
expect(res.statusCode).to.equal(200)
})
})
context('when a non-existant species is requested', () => {
const options = { query: { species: 'unicorn' } }
it('returns a 404 response', async () => {
const { res } = await expressRequestMock(subject, options)
expect(res.statusCode).to.equal(404)
})
})
context('when an error happens', () => {
const options = { query: {} }
it('calls the fallthrough function with the error', async () => {
try {
await expressRequestMock(subject, options)
} catch (error) {
expect(error.name).to.equal('NoSpeciesProvided')
}
})
})
})
License
express-request-mock is MIT licensed.