sinon trying to spy express res object

I'm trying to test this simple express middleware function

function onlyInternal (req, res, next) {
  if (!ReqHelpers.isInternal(req)) {
    return res.status(HttpStatus.FORBIDDEN).send() <-- TRYING TO ASSERT THIS LINE
  }
  next()
}

This is my test currently

describe.only('failure', () => {
      let resSpy
      before(() => {
        let res = {
          status: () => {
            return {
              send: () => {}
            }
          }
        }

        resSpy = sinon.spy(res, 'status')
      })

      after(() => {
        sinon.restore()
      })

      it('should call next', () => {
        const result = middleware.onlyInternal(req, resSpy)
        expect(resSpy.called).to.be.true
      })
    })

And i'm getting this error: TypeError: res.status is not a function

Why is res.status not a function? It clearly looks like a function to me..

1 answer

  • answered 2018-07-20 21:31 Zbigniew Zagórski

    sinon.spy returns newly created spy, not res that has new spy applied.

    So in your case: resSpy === res.status and not as you would expected resSpy === res, that wouldn't make sense.

    In other words, you should still pass original res to you middleware:

    const result = middleware.onlyInternal(req, res);