Giter Club home page Giter Club logo

express-unit's Introduction

express-unit

Express middleware testing made easy.

Build Status Coverage Status Dependency Status Dev Dependency Status Greenkeeper badge

λ npm install express-unit

Contents


Usage

Express Unit exports a helper function for running a single middleware. To use, just import it and pass it a setup function, your middleware, and an optional callback.

import run from 'express-unit'

run(setup|null, middleware[, callback])

Parameters

  • setup - A function defined to set up the Request/Response lifecycle before it enters middleware. Pass null if not needed. setup is called with three arguments:
    • req - A dummy Request object.
    • res - A dummy Response object.
    • next - A function used to proceed to middleware.
  • middleware - The middleware function under test. Passed different arguments depending on whether it is an "error handling" middleware.
    • err - forwarded from next(err) in setup if the middleware is an error handler.
    • req - The dummy Request object visited by setup.
    • res - The dummy Response object visited by setup.
    • next - A function used to signal the completion of the middlware.
  • callback - An optional function used to inspect the outcome of passing the Request/Response lifecycle through setup and middleware.
    • err - Forwarded from next(err) in middleware (if any).
    • req - The dummy Request object visited by setup and middleware.
    • res - The dummy Response object visited by setup and middleware.
import run from 'express-unit'
import { expect, spy } from './test-utils'
import myMiddleware from './my-middleware'

describe('myMiddleware', () => {
  it('gets called!', () => {
    const setup = spy((req, res, next) => next())
    const middleware = spy(myMiddleware)
    run(setup, middleware)
    expect(setup).to.have.been.calledBefore(middleware)
  })
})

setup

Your setup function will be called with a req, res, and next to prepare the request lifecycle for your middleware. This is your opportunity to set headers on req or spy/stub any relevant methods on res. Call next to execute your middleware.

If for some reason you don't want to supply a setup, just pass null.

run(null, middleware[, callback])
// middleware.js
export default function middleware(req, res, next) {
  const token = req.get('x-access-token')
  if (token) return next()
  const err = new Error('where is your token?')
  next(err)
}
// middleware.test.js
describe('middleware', () => {
  describe('when the request has a token header', () => {
    const setup = (req, res, next) => {
      req.headers['x-access-token'] = 'myToken'
      next()
    }
    it('calls next without error', done => {
      run(setup, middleware, done)
    })
  })
})

Callback

Express Unit supports callbacks. Pass a callback as the third argument to inspect the results.

// middleware.js
export default function middleware(req, res, next) {
  const token = req.get('x-access-token')
  if (token) return next()
  const err = new Error('Access token required.')
  return next(err)
}
// middleware.test.js
describe('middleware', () => {
  describe('when the request does not have a token header', () => {
    it('passes an Error', done => {
      run(null, middleware, (err, req, res) => {
        expect(err)
          .to.be.an('error')
          .with.property('message', 'Access token required.')
        done()
      })
    })
  })
})

Async/Await

Express Unit also supports async middleware. This is any middleware that is an async function or simply returns a Promise. express-unit will resolve an array of [err, req, res] that you can either await or receive in a call to then. Works great with express-async-wrap.

// middleware.js
import wrap from 'express-async-wrap'

export const middleware = users => wrap(async ({ params }, res, next) => {
  const { userId } = params
  const user = await users.findById(userId)
  if (!user) throw new NotFound(`User ${userId} does not exist.`)
  res.locals.user = user
  next()
})
// middleware.test.js
describe('middleware', () => {
  const user = { id: 1, name: 'foo' }
  afterEach(() => {
    users.findById.restore()
  })
  describe('when the user is found', () => {
    const setup = (req, res, next) => {
      req.params.userId = 1
      stub(users, 'findById').resolves(user)
      next()
    }
    it('sets the user on locals', async () => {
      const [ err, , res] = await run(setup, middleware(users))
      expect(err).to.be.null
      expect(users.findById).to.have.been.calledWith(user.id)
      expect(res.locals).to.have.property('user', user)
    })
  })
})

Why Express Unit?

Express Unit puts the "unit" back in unit testing for Express.js apps. It's a small, simple helper for exercising individual middleware functions in isolation. Most testing tutorials and examples for express apps will utilize supertest (or similar).

import request from 'supertest'
import app from '../app'

describe('app', () => {
  describe('/hello-test', () => {
    it('handles GET requests', done => {
      request(app)
        .get('/hello-test')
        .set('Accept', 'application/json')
        .expect(200, (err, res) => {
          /* make more assertions */
          done()
        })
    })
  })
})

This is great for testing your entire app or a given router within your app. For some endpoints, various middleware functions are put in place to determine the response, e.g. confirming a user's identity, verifying their access rights, and bailing out of a request early if preconditions are not met. But testing all of this in concert is integration testing, which is often best left at testing the "happy path". A single route could employ a middleware stack like this:

router
  .use(authorize)
  .route('/users/:userId/permissions')
  .put(userIs('admin'), updatePermissions(permissions))

router
  .use(errorHandler(logger))

There are 4 different middleware functions involved in this single route. At least one of which needs access to some kind of data store. But each middleware is very focused and can be reused or replaced (Yay!).

express-unit's People

Contributors

greenkeeper[bot] avatar thebearingedge avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

express-unit's Issues

Add set method to Request.

function Request() {
  // other stuff
  this.set = function set(header, value) {
    this.headers[header.toLowerCase()] = value
  }
}

Upgrade to v2.

  • Update dependencies and run tests.
  • Update engines to node 8 and npm 5
  • Remove extra dependencies.
  • Migrate to nyc for coverage.
  • Close pending Greenkeeper PRs.
  • Disable package-lock.json.
  • Code review.
  • Refactor Promises to async/await.
  • Lock coverage to 100%.
  • Update README.md.
  • Migrate to Codecov.
  • Publish major release.

Object/calledNext Proposal

Object/calledNext Proposal

Overview

Note

I might just be going about this the wrong way. If this seems logical to you I would like to send you a pull request with the changes.
I suppose if I make my errors JSON strings I wouldn't care about calledNext which might be a better route.

Proposal

  1. Return an object instead of an array
  2. Return a "calledNext" boolean

Positives

For "Tests Example 1"

  • One less line of code for every route that calls res.sendStatus

For "Tests Example 2"

  • As ugly as (await result()).err is its more readable then (await result())[0]
    • This code might be ugly enough to justify never writing it in the first place.

Negatives

  • Brakes the ENTIRE API
  • calledNext will make no sense in synchronouse use of the library and would be a false flag.
    • I think it would have to omit calledNext if called in a none promise form.

Code that needs the test

const userWithId = users => wrap(async ({ body: {id} }, res, next) => {
  const exists = await users.isId(id)
  if (!exists) return res.sendStatus(400)
  next()
})

I was messing around with explicit descriptions and minimal code so there is 2 different styles here but all the example do the same 3 tests

(Tests) Example 1: Less Code Less Explicit Test Descriptions

Current

context('when the user is found', () => {
  it(`advanced to the next middleware`, async () => {
    const setup = (req, res, next) => {
      req.body.id = 5
      res.sendStatus = stub()
      stub(users, 'isId').returns(Promise.resolve(true))
      next()
    }
    const [ err, , res ] = await run(setup, middleware)
    expect(err).to.equal(null)
    expect(res.sendStatus.called).to.equal(false)
    expect(users.isId).to.have.been.calledWith(5)
  })
})

Proposed

// Perposal Example with shorter less explicit
context('when the user is found', () => {
  it(`advanced to the next middleware`, async () => {
    const setup = (req, res, next) => {
      req.body.id = 5
      stub(users, 'isId').returns(Promise.resolve(true))
      next()
    }
    const { err, res, calledNext } = await run(setup, middleware)
    expect(err).to.equal(null)
    expect(calledNext).to.equal(true)
    expect(users.isId).to.have.been.calledWith(5)
  })
})

(Tests) Example 2: More Code More Explicit Test Descriptions

Current

context('when the user is found', () => {
  const setup = (req, res, next) => {
    req.body.id = 5
    stub(users, 'isId').returns(Promise.resolve(true))
    next()
  }
  const result = () => run(setup, middleware)

  it('calls next middleware', (done) => { run(setup, middleware, done) })
  it(`doesn't error out`, async() => {
    expect( (await result())[0] ).to.equal(null)
  })
  it(`calls users.isId`, async () => {
    await result()
    expect(users.isId).to.have.been.calledWith(5)
  })
})

Proposed

context('when the user is found', () => {
  const setup = (req, res, next) => {
    req.body.id = 5
    stub(users, 'isId').returns(Promise.resolve(true))
    next()
  }
  const result = () => run(setup, middleware)

  it('calls next middleware', (done) => { run(setup, middleware, done) })
  it(`doesn't error out`, async() => {
    expect( (await result()).err ).to.equal(null)
  })
  it(`calls users.isId`, async () => {
    await result()
    expect(users.isId).to.have.been.calledWith(5)
  })
})

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml
  • The new Node.js version is in-range for the engines in 1 of your package.json files, so that was left alone

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

res is just being passed instead of actually returned in callbacks

AssertionError: expected { Object (app, locals, ...) } to equal 422
or
expected [Function] to equal 422
etc.

When trying to:

            const setup = spy((req, res, next) => {
                // setting headers
                next();
            });

            run(setup, checkIfSubmitted, (err, req, res) => {
                expect(res).to.have.status(422);
                done();
            });

I have tried those assertions: expect(res).to.have.status(422);, expect(res.status).to.be.equal(422), expect(res.status()).to.be.equal(422), etc.

Anything I am missing? The middlware is simple:

export function checkIfSubmitted(req, res, next) {
    return res.status(422).json({'test': 'test'});
}

Basically - it gets the original res in the callback. The middleware gets called from test (I can console.log from it) and if I run it through Postman - it successfully sets 422.

An in-range update of es6-error is breaking the build 🚨

Version 4.1.0 of es6-error was just published.

Branch Build failing 🚨
Dependency es6-error
Current Version 4.0.2
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

es6-error is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Commits

The new version differs by 3 commits.

  • 531da4b 4.1.0
  • 344e9be Merge pull request #36 from LKay/feature/lkay/improve-build
  • 66989ed Update dependencies and improve build

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

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.