Giter Site home page Giter Site logo

danawoodman / sinon-express-mock Goto Github PK

View Code? Open in Web Editor NEW
47.0 5.0 16.0 61 KB

Simple request and response mock objects to pass into Express routes when testing using Sinon.

Home Page: https://www.npmjs.com/package/sinon-express-mock

License: MIT License

JavaScript 100.00%
sinon epub mock test testing helper util utility router route

sinon-express-mock's Introduction

sinon-express-mock

Simple request and response mock objects to pass into Express routes when testing using Sinon.

The mock objects attach Sinon spys to request methods. See src/index.js for a full list of stubbed out methods.

Install

npm install --save-dev sinon-express-mock sinon

Depends on:

  • Node v4+ (or Object.assign support needed)
  • Sinon

Usage

Contents of src/foo.js:

export default (req, res) => {
  res.json({ foo: req.body.foo })
}

Contents of test/foo-test.js:

import route from '../src/foo'
import chai, { expect } from 'chai'
import sinonChai from 'sinon-chai'
import { mockReq, mockRes } from 'sinon-express-mock'

chai.use(sinonChai);

describe('my route', () => {
  it('should foo the bar', () => {
    const request = {
      body: {
        foo: 'bar',
      },
    }
    const req = mockReq(request)
    const res = mockRes()

    route(req, res)

    expect(res.json).to.be.calledWith({ foo: request.body.foo })
  })
})

Changelog

v2.0.3

  • res.write() is now stubbed.

v2.0.0

  • Make sinon a peerDependency.

v1.3.1

  • Bundle fix from #3

pre v1.3.1

  • Changelog didn't exist! ๐Ÿ˜ฑ

Credits

Dana Woodman and contributors

License

MIT

sinon-express-mock's People

Contributors

anshulsahni avatar boazdavid avatar craigsimko avatar danawoodman avatar digli avatar jessicamrbr avatar nicogreenarry avatar petterive avatar tracker1 avatar yjimk 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  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

sinon-express-mock's Issues

Unlisted dependencies?

The example code uses

expect(res.json).to.be.calledWith({ foo: request.body.foo.bar })

but only imports

import route from "../src/foo" import { mockReq, mockRes } from "sinon-express-mock"

Where is "expect" coming from? chai-http has an expect().to.be.calledWith method, but just using it in conjunction with the example code still throws the same error.

Mocked next?

What's the recommended way to handle routes that use next for error handling?

Example test missing sinon-chai library

expect(res.json).to.be.calledWith({ foo: request.body.foo }) is syntax from the sinon-chai library, and only worked with the following:

const chai = require('chai');
const sinonChai = require('sinon-chai');
const expect = chai.expect;
chai.use(sinonChai);

Verifying the response state (without knowing how it is set by the implementation)?

As an example of the kind of I'm wanting to do: say I check the return code of a route, something like this:

    // Handler definition
   const route = (req, res) => {
        res.send({name: 'foo'}); // implies status 200
    };
   // Test
   describe('#/api/user', function() {
        it('should get the username', () => {
            const req = mockReq();
            const res = mockRes();
            route(req, res);

            expect(res.statusCode).to.equal(200); // check the return code is 200 OK
            // ...
        });
    });

However, the stub request object has no internal state like a real request would. I don't want to build in the requirement that the res#statusCode method is actually called explicitly (not least because there's a #status alias, and possibly other things going on internally). So what I imagine is an extremely common case is difficult to verify.

This generalises to all the other methods of Request and Response objects which return internal state. It looks like the stub objects need to wrap real ones for this to be achievable correctly.

But possibly this has been anticipated and there's an easy workaround that makes res.statusCode return 200 by default, or something else if a status code was set - just not documented?

peerDependency warning for [email protected]

Hi there!

Pleased to be using your library in our project, however I keep receiving peerDep warnings from npm

npm WARN [email protected] requires a peer of [email protected] but none is installed. You must install peer dependencies yourself.

We're using [email protected] and this library still works a treat. Would it be alright if the peerDep was changed to "^4.1.3" to catch the other minor versions in sinon v4? Submitting a PR for this one now

Persist mutations to locals

Locals can not currently be mutated after their assignment. This causes issues when testing the following:

const middleware = (req, res, next) => {
  res.locals.myVar = "new";
  next();
};

const req = mockReq();
const res = mockRes({ locals: { myVar: "old" } });

middleware(req, res, spy());

res.locals.myVar // "old"

This is useful to test as some middleware can be reliant on previous middleware setting locals (such as decoding tokens).

@danawoodman I noticed from #12 that you mentioned you're not actively maintaining this repo anymore, in which case I'll get around to this when I get a chance. Otherwise if anyone else notices this I'm happy for them to pick this up.

Unmet peer dependency [email protected] (revisited)

I don't think I can reopen issue #10 now you've closed it, and perhaps you don't get notifications when I add comments to it.

So, to recapitulate what I said there: I think this issue is still unresolved: package.json's peerDependencies is still configured as ^4.1.3.

chainable functions

suppose i were testing this route handler

// myroute.js
module.exports = function(req, res) {
    return res.status(200).end()
}

with this test case

it('should call end', function() {
    var myroute = require('./myroute')
    var res = mockRes()
    myroute(null, res)
    expect(res.end).to.be.called
})
// TypeError: Cannot read property 'end' of undefined

the type error being thrown is because the stubbed res.status function is a sinon spy and does not return res. could it be possible to alter this library to support chaining function calls in a backwards compatible manner?

i'd be happy to have a go at adding this, just wanted to get your thoughts on the matter ๐Ÿ™

Unmet peer dependecy: [email protected]

I gather sinon-express-mock currently lists sinon ^4.1.3 as a peer dependency.

Sinon's current release is now 5.0.7.

Is there a plan to update to, or otherwise allow current Sinon releases? Or do I need to downgrade Sinon to use sinon-express-mock?

Thanks!

mockNext?

It would be nice to have the mock for the next() function.
I am testing some middleware in typescript and it would be useful.

I can make a PR if you'd like.

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.