jeudi 30 août 2018

Stubbing express middleware functions with sinon is

I'm trying to use sinon stubbing via callsFake function, just as it's advised from their most updated docs.

Even though I'm requiring the module and replacing the function from the property at the export. I keep seeing the original function behavior acting.

I know that I should try to get the function stubbed before the middlewares get setup, and that's when express app is first imported.

This is the function I'm trying to stub, defined as a function and exported as a object too. It's defined in a script file with a path like api/middlewares/stripe/signature.

const stripeHelper = require('../../../lib/stripe')
const logger = require('../../../lib/logger')
const verifySignature = (req, res, next) => {
  let event
  let eventName = req.url.replace('/', '')
  try {
      // Try adding the Event as `request.event`
    event = stripeHelper.signatureCheck(
        eventName,
        req.body,
        req.headers['stripe-signature']
      )
  } catch (e) {
      // If `constructEvent` throws an error, respond with the message and return.
    logger.error('Error while verifying webhook request signature', e.message, e)
    return res.status(400).send('Webhook Error:' + e.message)
  }
  req.event = event
  next()
}
module.exports.verifySignature = verifySignature

Then I've tried to stub such middleware this way:

before(function (done) {
  verifySignatureStub = sinon.stub(signatureMiddleware, 'verifySignature')
  rawStub = sinon.stub(bodyParser, 'raw')
  rawStub.callsFake(function (req, res, next) {
    return next()
  })
  verifySignatureStub.callsFake(function (req, res, next) {
    const {customerId} = req.params.customerId
    const subscriptionId = req.params.subscriptionId
    const planId = req.params.planId
    req.event = generateEventFromMock('invoice.payment_failed', {subscriptionId, customerId, planId})
    return next()
  })
  done()
})

after(function (done) {
  verifySignatureStub.restore()
  rawStub.restore()
  done()
})

In my test I'm trying to make sure app, my express instance is just required AFTER the stubs are set.

Tried in different ways but always seeing the original middleware function acting instead of the replace stub I'm trying to get used.

Particularly, tried to:

  • Defined the stub within a before hook at my test file BEFORE requiring app
  • Getting a bootstrap.test.js file and require it at a mocha.opts file
  • Manually require a file with such hooks ay my test file

None of these worked so far, always seeing the original function executed.

Any suggestions or ideas?

Aucun commentaire:

Enregistrer un commentaire