1

I have Node.js code that writes a message to an SWS queue. I'm trying to stub this code in my unit tests.

Source:

var AWS = require('aws-sdk');
var sqs = new AWS.SQS({apiVersion: '2012-11-05'});
sqs.sendMessage(myMessage, function(err, data) {
    if (err) {
      console.log("Error", err);
  });

In My unit tests I'm trying to do something like this to stub the call:

sandbox = sinon.createSandbox();
sandbox.stub(AWS.SQS,'sendMessage').callsFake((message,fn) => {
  console.log("Stub AWS sendMessage");
});
sandbox.restore();

I am getting this error: TypeError: Cannot stub non-existent own property sendMessage

ChrisRTech
  • 547
  • 8
  • 25
  • Check out this [SO question](https://stackoverflow.com/questions/26243647/sinon-stub-in-node-with-aws-sdk), it includes a link to an npm module that mocks out all the AWS SDK services, and examples for stubbing them – half of a glazier Jan 15 '20 at 10:00

2 Answers2

0

A similar question has been asked here.

You can use the aws-sdk-mock package.

It's really easy to use. Just call AWS.mock with the service, method and a stub function.

AWS.mock('SQS', 'sendMessage', function(params, callback) {
    callback(null, 'success'); 
});
j-petty
  • 2,668
  • 1
  • 11
  • 20
0
const AWS = require("aws-sdk");
const sinon = require("sinon");

describe("dummy describe", () => {

  beforeEach(() => {
    // use this if you want to stub SQS for all the iteration
    sinon.stub(AWS, "SQS").returns({
      sendMessage() {
        return {
          promise() {
            return Promise.resolve();
          }
        };
      }
    });
  });

  afterEach(() => {
    sinon.restore(); // use this to restore the stubbed function
  });

  it("dummy test success", async () => {
    sinon.stub(AWS, "SES").returns({ // this is what you need
      sendRawEmail() {
        return {
          promise() {
            return Promise.resolve();
          }
        };
      }
    });
  });
});

For more check this

Debu Shinobi
  • 2,057
  • 18
  • 21