Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

javascript - Sinon.JS stub a function that resolves a promise

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...