Sinon.JS stub a function that resolves a promise

☆樱花仙子☆ 提交于 2019-12-14 03:22:15

问题


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.


回答1:


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 
}


来源:https://stackoverflow.com/questions/44712649/sinon-js-stub-a-function-that-resolves-a-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!