Node.js stubbing AWS S3 method in query spec with sinon

I have a based application express

running on node.js 0.12.2

that uses a method s3.headBucket

from aws-sdk 2.1.22

to return a JSON response depending on whether a particular bucket exists or not.

I am struggling to directly disable the call s3.headBucket

using sinon. I managed to get around this by creating an s3wrapper module that only requires aws-sdk

and instantiates and returns a variable s3

, however I'm pretty sure it can be done without using a wrapper module and can instead be trimmed directly with sinon, can anyone point me to the correct one direction?

Below is the current working code (with a wrapper module s3wrapper.js

I would like to remove and handle the stubbing in my file status_router_spec.js

). In other words, I would like to be able to call s3.headBucket({Bucket: 'whatever' ...

instead s3wrapper.headBucket({Bucket: ' ...

and be able to disable that call s3.headBucket

with my own answer.

status_router_spec.js

var chai = require('chai'),
    sinon = require('sinon'),
    request = require('request'),
    myHelper = require('../request_helper')

var expect = chai.expect

var s3wrapper = require('../../helpers/s3wrapper')

describe('My router', function () {
  describe('checking the service status', function () {
    var headBucketStub

    beforeEach(function () {
      headBucketStub = sinon.stub(s3wrapper, 'headBucket')
    })

    afterEach(function () {
      s3wrapper.headBucket.restore()
    })

    describe('when no errors are returned', function () {
      it('returns healthy response', function (done) {
        // pass null to represent no errors
        headBucketStub.yields(null)

        request.get(myHelper.appUrl('/status'), function (err, resp, body) {
          if (err) { done(err) }
          expect(JSON.parse(body)).to.deep.eql({
            healthy: true,
            message: 'success'
          })
          done()
        })
      })
    })
  })
})

      

s3wrapper.js

var AWS = require('aws-sdk')
var s3 = new AWS.S3()

module.exports = s3

      

status_router.js

var Router = require('express').Router

var s3wrapper = require('../helpers/s3wrapper.js')

var router = new Router()

function statusHandler (req, res) {     
  s3wrapper.headBucket({Bucket: 'some-bucket-id'}, function (err) {
    if (err) {
      return res.json({ healthy: false, message: err })
    } else {
      return res.json({ healthy: true, message: 'success' })
    }
  })
}

router.get(/^\/status\/?$/, statusHandler)

module.exports = router

      

+3


source to share





All Articles