๐Ÿ“ฆ antongolub / reqresnext

Tiny helper for express middleware testing

โ˜… 7 stars โ‘‚ 2 forks ๐Ÿ‘ 7 watching โš–๏ธ MIT License
๐Ÿ“ฅ Clone https://github.com/antongolub/reqresnext.git
HTTPS git clone https://github.com/antongolub/reqresnext.git
SSH git clone git@github.com:antongolub/reqresnext.git
CLI gh repo clone antongolub/reqresnext
semantic-release-bot semantic-release-bot chore(release): 1.7.0 [skip ci] 7588d0c 3 years ago ๐Ÿ“ History
๐Ÿ“‚ master View all commits โ†’
๐Ÿ“ flow-typed
๐Ÿ“ src
๐Ÿ“ typings
๐Ÿ“„ .babelrc
๐Ÿ“„ .eslintrc
๐Ÿ“„ .flowconfig
๐Ÿ“„ .gitignore
๐Ÿ“„ .npmignore
๐Ÿ“„ .nycrc
๐Ÿ“„ .travis.yml
๐Ÿ“„ CHANGELOG.md
๐Ÿ“„ LICENSE
๐Ÿ“„ package.json
๐Ÿ“„ README.md
๐Ÿ“„ TODO.md
๐Ÿ“„ README.md

reqresnext

Build Status npm (tag) Maintainability Test Coverage js-standard-style

Tiny helper for expressjs middlewares testing.

Motivation
There're several nice mocking tools for express/connect. The best of them (imho) is node-mocks-http by Howard Abrams. This lib brings constructors, that accurately reproduces logic of express classes. That's pretty cool, but sometimes you need a bit more.

Reqresnext:

  • Just uses express proto directly. So you get not just similar, but exactly the same behaviour as in production.
  • Exposes the only additional property to verify outgoing data โ€” res.body.

Install

npm add reqresnext -D
yarn add reqresnext -D

Usage

import reqresnext from 'reqresnext'
 
    it('middleware does something', () => {
      const {req, res, next} = reqresnext(<ReqOptions>, <ResOptions>)
      mware(req, res, next)
 
      expect(res.statusCode).toEqual('...')
      expect(res.body).toEqual('...')
    })

Request & Response

Also you may construct req/res instances directly:
import {Response, Request} from 'reqresnext'

    const foo = {name: 'foo', value: 'bar', options: {}}
    const res = new Response({cookies: [foo]})
    
    expect(res.get('Set-Cookie')).toEqual('foo=bar; Path=/')
Supported options are described in interface. The main ones:
// cookies
    const foo = {name: 'foo', value: 'bar', options: {}}
    const res = new Response({cookies: [foo]})

// headers
    const req = new Request({headers: {foo: 'bar', baz: 'qux'}})

// url
    const req = new Request({url: 'https://example.com'})

Any additional props that does not intersect with proto are injected as is.

const res = new Response({foo: 'bar', baz: 1, ...})
    res.foo // 'bar'

next() handler

Next handler may be wrapped with spy anytime: before or after reqresnext. If function is specified, the factory just passes it back.
const handler = chai.spy(() => {})
    const {next} = reqresnext({}, {}, handler)
    
    next === handler // true