Code Monkey home page Code Monkey logo

mock-req-res's Introduction

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

Development 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.

mock-req-res's People

Contributors

davesag avatar dependabot[bot] avatar gcgarrett avatar greenkeeper[bot] avatar greenkeeperio-bot avatar jkeyes avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

mock-req-res's Issues

An in-range update of nyc is breaking the build 🚨

The devDependency nyc was updated from 14.1.0 to 14.1.1.

🚨 View failing branch.

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

nyc is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

Commits

The new version differs by 9 commits.

  • fe3311b chore(release): 14.1.1
  • 85ec479 docs: Link to test-exclude in place of inline list of default excludes [skip ci] (#1109)
  • 57debc1 fix(cli): Report error if unwanted positional arguments are received (#1100)
  • b3dfae8 docs: Point to updated location of default exclude list (#1107)
  • 0cc7309 docs(readme): Fix Slack badge image insecure content warning [skip ci] (#1105)
  • 3cdfb8e docs: Mention extension in the CHANGELOG about exclude-after-remap
  • b5b67de fix(check-coverage): make the --temp-dir option visible (#1101)
  • 21fe1e7 chore: Regenerate snapshots for tap >= 12.6.3 (#1098)
  • 65478be docs: Reorganize readme (#1093)

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 🌴

An in-range update of @stryker-mutator/core is breaking the build 🚨


🚨 Reminder! Less than one month left to migrate your repositories over to Snyk before Greenkeeper says goodbye on June 3rd! 💜 🚚💨 💚

Find out how to migrate to Snyk at greenkeeper.io


The devDependency @stryker-mutator/core was updated from 3.1.0 to 3.2.1.

🚨 View failing branch.

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

@stryker-mutator/core is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: build: Your tests failed on CircleCI (Details).

Commits

The new version differs by 101 commits.

  • 763c52f v3.2.1
  • 575bd8f build(deps-dev): bump ts-json-schema-generator from 0.67.1 to 0.68.0 (#2203)
  • 90fa206 chore(html-reporter): remove the stub package (#2200)
  • 5d255fb test(api): remove useless integration tests (#2201)
  • e18e5f8 build(deps-dev): bump @types/semver from 7.1.0 to 7.2.0 (#2204)
  • 8b9cc1f build(deps): bump tslib from 1.12.0 to 2.0.0 (#2205)
  • 3f09a50 test(e2e): add e2e test for vue-cli with jest (#2206)
  • 95c4e78 test(e2e): add e2e test for vuecli with typescript and mocha (#2202)
  • 45f2839 build(deps-dev): bump typescript from 3.8.3 to 3.9.2 (#2194)
  • b06d6d0 build(deps): bump commander from 4.1.1 to 5.1.0 (#2168)
  • c695c1f chore: add .gitattributes file for line endings (#2199)
  • 26beff2 fix: remove duplicate package.json script (#2198)
  • 34b31e9 v3.2.0
  • 61953c7 feat(init): add reference to mono schema (#2162)
  • a2d3e8b build(deps-dev): bump @types/node from 13.13.6 to 14.0.1 (#2190)

There are 101 commits in total.

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 🌴

An in-range update of @stryker-mutator/mocha-framework is breaking the build 🚨

The devDependency @stryker-mutator/mocha-framework was updated from 2.0.1 to 2.0.2.

🚨 View failing branch.

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

@stryker-mutator/mocha-framework is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

Commits

The new version differs by 10 commits.

  • 607bddf v2.0.2
  • 3fd5db9 fix(child process): cleanup after dispose (#1636)
  • 4324d9f fix(child process proxy): OutOfMemory detection (#1635)
  • 124ef6a fix(dispose): fix raise condition in dispose action
  • 4349867 build(deps-dev): update webpack requirement from ~4.34.0 to ~4.35.3 (#1627)
  • d85dad3 build(deps): update semver requirement from ~6.1.0 to ~6.2.0 (#1616)
  • 92b98dc build(deps): update log4js requirement from ~4.3.0 to ~4.4.0 (#1602)
  • fd64c92 build(deps): update inquirer requirement from ~6.3.1 to ~6.4.1 (#1599)
  • a8f8435 build(deps-dev): update tslint requirement from ~5.17.0 to ~5.18.0 (#1598)
  • f6612eb refactor(tslint): match basarat styleGuide (#1594) (#1615)

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 🌴

Cannot read `res.body` after calling async function.

With the following implementation, the function getRooms was called when running the test case. However, I cannot read the body of the response object after the function getRooms was called.
Target Function

class RoomHandle {
    static async getRooms(req, res) {
        const hotelCode = req.session.hotel_code;
        const result = await Rooms.findByHotelCode(hotelCode.toString());
        res.send({ rooms: result.Items, count: result.Count, status: 'success' });
    }
}

Test

const { expect } = require('chai');
const { mockRequest, mockResponse } = require('mock-req-res')
const RoomHandle = require('../controllers/RoomHandle');

describe('RoomHandle', () => {
    context('To', () => {
        const res = mockResponse();
        const req = mockRequest({ 
            session: {
                hotel_code: '234'
            }
        });
        
        before(async ()=>{
            await RoomHandle.getRooms(req, res);
        })

        console.log(res.body); // <=== undefined

        it('get room list with RoomHandle.getRooms', () => {        
            expect(res.body.status).to.equal('success')
            expect(res.body.rooms.Count).to.equal(1)
        });
    })

});

An in-range update of eslint-plugin-promise is breaking the build 🚨

The devDependency eslint-plugin-promise was updated from 4.1.1 to 4.2.1.

🚨 View failing branch.

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

eslint-plugin-promise is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

Commits

The new version differs by 6 commits.

  • 5b935bd 4.2.1
  • 9017a70 4.2.1
  • 254c0fd 4.2.0
  • 3f2c61d Merge pull request #136 from ota-meshi/fix/no-return-wrap
  • 57267ca Add testcase
  • d8b9206 Fixed that no-return-wrap does not work if type is not "ExpressionStatement".

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 🌴

An in-range update of ajv is breaking the build 🚨

The devDependency ajv was updated from 6.6.2 to 6.7.0.

🚨 View failing branch.

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

ajv is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

Release Notes for v6.7.0

Option useDefaults: "empty" to replace null and "" (empty strings) with default values.
Update draft-04 meta-schema to remove incorrect usage of "uri" format.

Commits

The new version differs by 17 commits.

There are 17 commits in total.

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 🌴

An in-range update of lint-staged is breaking the build 🚨

The devDependency lint-staged was updated from 8.1.6 to 8.1.7.

🚨 View failing branch.

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

lint-staged is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

Release Notes for v8.1.7

8.1.7 (2019-05-15)

Bug Fixes

  • Resolve security vulnerability in dependencies (#615) (315890a), closes #600
Commits

The new version differs by 2 commits.

  • 315890a fix: Resolve security vulnerability in dependencies (#615)
  • cbf0e0e docs: Correct section about filtering files (#612)

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 🌴

An in-range update of @stryker-mutator/core is breaking the build 🚨

The devDependency @stryker-mutator/core was updated from 1.2.0 to 1.3.0.

🚨 View failing branch.

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

@stryker-mutator/core is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

Commits

The new version differs by 26 commits.

  • f42a70f v1.3.0
  • b4336fb feat(files): use mocha 6's way of resolving files (#1512)
  • 31ee085 fix(dispose): clean up child processes in alternative flows (#1520)
  • 3c83bbe feat(onScoreCalculated): deprecate onScoreCalculated reporter event (#1513)
  • baa374d feat(mocha 6): support all config formats (#1511)
  • fd399a8 docs: specify minimum NodeJS version (#1510)
  • 70ffa61 build: use fs instead of mz in performance tests (#1507)
  • 025fe9d build(deps-dev): update nyc requirement from ^13.0.1 to ^14.0.0 (#1505)
  • b282291 Merge pull request #1504 from stryker-mutator/dependabot/npm_and_yarn/tslint-approx-5.16.0
  • 04e7e0b build(deps-dev): update tslint requirement from ~5.15.0 to ~5.16.0
  • 955dc42 Merge pull request #1496 from stryker-mutator/dependabot/npm_and_yarn/inquirer-approx-6.3.1
  • c74e98e build(deps): update inquirer requirement from ~6.2.0 to ~6.3.1
  • dd72bac Merge pull request #1495 from stryker-mutator/dependabot/npm_and_yarn/prettier-approx-1.17.0
  • b7e68d0 build(deps-dev): update webpack requirement from ~4.29.1 to ~4.30.0 (#1497)
  • 90307e7 build(deps): update istanbul-lib-instrument requirement (#1500)

There are 26 commits in total.

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 🌴

An in-range update of @stryker-mutator/mocha-framework is breaking the build 🚨

The devDependency @stryker-mutator/mocha-framework was updated from 2.0.0 to 2.0.1.

🚨 View failing branch.

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

@stryker-mutator/mocha-framework is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

Commits

The new version differs by 15 commits.

  • d053be5 v2.0.1
  • ff2ccfc build(ci): disable execa timeout to prevent failing perf job (#1604)
  • 5916b40 refactor(file names): align on file names (#1605)
  • fb858ca fix(html): set utf-8 charset (#1592)
  • d365a47 build(deps-dev): update tslint requirement from ~5.16.0 to ~5.17.0 (#1570)
  • 66b3f9f build(deps-dev): update webpack requirement from ~4.32.2 to ~4.34.0 (#1584)
  • 4d79580 build(deps): update typed-rest-client requirement from ~1.4.0 to ~1.5.0 (#1580)
  • e267c31 build(deps): update tslib requirement from ~1.9.3 to ~1.10.0 (#1582)
  • 263da6d build(deps-dev): update raw-loader requirement from ~2.0.0 to ~3.0.0 (#1576)
  • 26ca753 build(ts): fix lint and pin ts version (#1577)
  • 4b130c2 build(deps): update istanbul-lib-instrument requirement (#1532)
  • a68ba8f build(deps): update semver requirement from ~6.0.0 to ~6.1.0 (#1555)
  • 42f98ac build(deps): update log4js requirement from ~4.2.0 to ~4.3.0 (#1556)
  • 1d17a87 build(deps-dev): update webpack requirement from ~4.31.0 to ~4.32.2 (#1557)
  • 37ca23c fix(inquirer): fix inquirer types (#1563)

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 🌴

An in-range update of @stryker-mutator/javascript-mutator is breaking the build 🚨

The devDependency @stryker-mutator/javascript-mutator was updated from 2.1.0 to 2.2.1.

🚨 View failing branch.

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

@stryker-mutator/javascript-mutator is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

Commits

The new version differs by 80 commits.

  • 4422086 v2.2.1
  • 58f8da4 chore: make release script executable
  • 650f58e v2.2.0
  • 067df6d feat(progress-reporter): show timed out mutant count (#1818)
  • 87012b6 docs: add code of conduct (#1766)
  • fab1786 build(deps-dev): Bump eslint-config-prettier from 6.4.0 to 6.5.0 (#1807)
  • 127be2f build(deps-dev): Bump eslint from 6.5.1 to 6.6.0 (#1809)
  • 834c6de build(deps-dev): Bump @babel/preset-env from 7.6.3 to 7.7.1 (#1825)
  • 8b390f5 build(deps): Bump @babel/traverse from 7.6.3 to 7.7.0 (#1823)
  • b7591c7 build(deps): Bump @babel/parser from 7.6.4 to 7.7.0 (#1822)
  • 7491c97 docs(build): make the CI build badge clickable (#1828)
  • a3de7cf build(deps-dev): Bump typescript from 3.5.3 to 3.7.2 (#1826)
  • bd8e1a6 build(deps): Bump @babel/generator from 7.6.4 to 7.7.0 (#1820)
  • 694093a remove misleading docs (#1827)
  • deecffa build(deps-dev): Bump @babel/types from 7.6.3 to 7.7.1

There are 80 commits in total.

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 🌴

An in-range update of @stryker-mutator/mocha-runner is breaking the build 🚨


🚨 Reminder! Less than one month left to migrate your repositories over to Snyk before Greenkeeper says goodbye on June 3rd! 💜 🚚💨 💚

Find out how to migrate to Snyk at greenkeeper.io


The devDependency @stryker-mutator/mocha-runner was updated from 3.1.0 to 3.2.1.

🚨 View failing branch.

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

@stryker-mutator/mocha-runner is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: build: Your tests failed on CircleCI (Details).

Commits

The new version differs by 101 commits.

  • 763c52f v3.2.1
  • 575bd8f build(deps-dev): bump ts-json-schema-generator from 0.67.1 to 0.68.0 (#2203)
  • 90fa206 chore(html-reporter): remove the stub package (#2200)
  • 5d255fb test(api): remove useless integration tests (#2201)
  • e18e5f8 build(deps-dev): bump @types/semver from 7.1.0 to 7.2.0 (#2204)
  • 8b9cc1f build(deps): bump tslib from 1.12.0 to 2.0.0 (#2205)
  • 3f09a50 test(e2e): add e2e test for vue-cli with jest (#2206)
  • 95c4e78 test(e2e): add e2e test for vuecli with typescript and mocha (#2202)
  • 45f2839 build(deps-dev): bump typescript from 3.8.3 to 3.9.2 (#2194)
  • b06d6d0 build(deps): bump commander from 4.1.1 to 5.1.0 (#2168)
  • c695c1f chore: add .gitattributes file for line endings (#2199)
  • 26beff2 fix: remove duplicate package.json script (#2198)
  • 34b31e9 v3.2.0
  • 61953c7 feat(init): add reference to mono schema (#2162)
  • a2d3e8b build(deps-dev): bump @types/node from 13.13.6 to 14.0.1 (#2190)

There are 101 commits in total.

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 🌴

An in-range update of eslint-plugin-import is breaking the build 🚨

The devDependency eslint-plugin-import was updated from 2.17.2 to 2.17.3.

🚨 View failing branch.

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

eslint-plugin-import is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

Commits

The new version differs by 25 commits.

  • cf5573b Bump to v2.17.3
  • caae65c [Tests] eslint 2 does not have linter.version
  • 557a3e2 [Deps] update resolve
  • 17beb33 Merge pull request #1356 from christophercurrie/typescript-declare
  • c8ac7ff [Docs] Document env option for eslint-import-resolver-webpack
  • c09c0ce Issue #1258 (docs)
  • 753c9db [refactor] fix eslint 6 compat by fixing imports
  • b52bf3e PR feedback
  • 7aa13d1 PR feedback
  • f66e064 Remove log messages
  • d1e4455 Verbose variable names
  • 67b1e95 Support older typescript parsers
  • 288cedf Make groups non-capturing.
  • aa290bb Improve support for Typescript declare structures
  • 1edbbd0 [Fix] no-common-js: Also throw an error when assigning

There are 25 commits in total.

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.