-1

I want to use Sinon to stub a function that uses callbacks which resolve a promise:

const callback = (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });

stub.me({}, callback);

I tried:

var stub = {
  me: sinon.stub().yieldsTo("resolve", "my_data"),
};

but I keep getting mocha timeouts.

The code doesn't define a const for callback. It's all in the stub.me function call. I just wrote it like that so it would be clear to read.

It's also wrapped in a new Promise((resolve,reject) => {} ); block.

stampede76
  • 1,521
  • 2
  • 20
  • 36
  • This doesn't make sense at all. A stub is a replacement for a function. That function (and its replacement) must be used from somewhere. If this is a module (say .`/my-module.js`) then you need to supply more code. What is it you are trying to test? – oligofren Jun 27 '17 at 15:43
  • 1
    AWS DynamoDB. I have a function that turns dynamodb-doc into a promise. I fixed it by using that AWS mocks. I tried it before, but missed the part that dynamo needs to be required in the scope of each individual function. I'll post an answer soon after I do more work on it. – stampede76 Jun 28 '17 at 17:49
  • I think your question is unclear an not useful to others. It's not clear what makes the `new Promise()` and how `stub` and `stub.me()` are defined. – try-catch-finally Jul 06 '17 at 05:16

1 Answers1

-2

This was due to a scope error. Per the docks for aws-sdk-mock, AWS service needs to be initialized in the function.

Does not work:

var AWS      = require('aws-sdk');
var sns      = AWS.SNS();
var dynamoDb = AWS.DynamoDB();

exports.handler = function(event, context) {
  // do something with the services e.g. sns.publish 
}

Works:

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

exports.handler = function(event, context) {
  var sns      = AWS.SNS();
  var dynamoDb = AWS.DynamoDB();
  // do something with the services e.g. sns.publish 
}
stampede76
  • 1,521
  • 2
  • 20
  • 36
  • 1
    No trace of `stub`, `me` or even `sinon`. Though this answer may have solved your problem it won't help others with a similar problem "stubbing functions" since your question does not show the whole picture and your answer does not refer to the stubbing at all. – try-catch-finally Jul 06 '17 at 05:19
  • So AWS SDK dynamo functions use callbacks. I used them to create a new function which used promises. I wanted to test the code locally, so I tried that aws-mock npm, which wasn't working. I followed their instructions to define the service inside my function,a nd it didn't work, so I switched to sinon. Sinon didn't work, so I posted that question. The more I explain it, the more complex it gets so I tried to keep it to the minimum. – stampede76 Jul 07 '17 at 02:30