0

I'm new to sinon and can't achieve the results I want.

I'm trying to stub AWS S3 API getObject to return a test-provided object.

My production code has:

let s3 = new AWS.S3({ apiVersion: '2006-03-01' });
let params = {
  Bucket: aws_bucket,
  Key: path
};

s3.getObject(params, function(err, data) {
    ...
    });

My test code has:

describe('GET /image', function() {
  beforeEach(function() {
    let stub = sinon.createStubInstance(AWS.S3);
    stub.getObject.callsFake(() => { console.log('stubbed'); });
  });

The AWS S3 class instance is fully stubbed when I run the test, which is great, but it is not calling my fake.

What am I missing?

jws
  • 2,171
  • 19
  • 30
  • Something related: https://stackoverflow.com/questions/32896770/stubbing-s3-uploads-in-node-js – jws Jul 21 '20 at 20:16

1 Answers1

0

I found a working approach.

Step 1 Wrap AWS.S3 instance in another module.

// s3.js

var AWS = require('aws-sdk');

var s3 = new AWS.S3({ apiVersion: '2006-03-01' });
module.exports = s3;

Step 2 Change production code to use this instance instead of making its own.

// image.js

var s3 = require('./s3');
// ... other code ...
s3.getObject(...);

Step 3 Stub what needs to be stubbed.

// image-test.js
var s3 = require('./s3');

var getObjectStub;

describe('GET /image', function() {
  beforeEach(function() {
    getObjectStub = sinon.stub(s3, 'getObject').callsFake(() => { console.log('stubbed'); });
  });

  afterEach(() => {
    getObjectStub.restore();
  });
  // test code continues
});
jws
  • 2,171
  • 19
  • 30