Reputation: 6259
Normally I use this code:
aws_stub.S3 = function(){};
var fake_aws_listObjects = function(params, func){func("failure", null)};
var fake_aws_listObjects_stub = sinon.spy(fake_aws_listObjects);
aws_stub.S3.prototype.listObjects = fake_aws_listObjects_stub;
To stub a function like the following one:
new AWS.S3().listObjects(that.build_params(), function(err, data) {
if(err){
that.make_failure_callback();
}
else{
that.add_keys(data);
if(data.IsTruncated){
that.make_request(data.NextMarker);
}else{
that.make_success_callback(that.keys);
}
}
});
The problem with this stubbing is that on each request it returns the same
Now I wanted to do is different stubbing for each call:
aws_stub.S3 = function(){};
var fake_aws_truncated = function(params, func){func(null, {
Contents: [{Key: "3fb252ba-0724-438c-93b6-8cd0fd972a8e/image/1:::2.jpg"}],
IsTruncated: true,
NextMarker: "nextMarker"
})};
var fake_aws_listObjects = function(params, func){func(null, {Contents: [{
Key: "3fb252ba-0724-438c-93b6-8cd0fd972a8e/image/2:::3.jpg"
}]})};
var fake_aws_listObjects_stub = sinon.stub();
fake_aws_listObjects_stub.onCall(0).returns(fake_aws_truncated);
fake_aws_listObjects_stub.onCall(1).returns(fake_aws_listObjects);
aws_stub.S3.prototype.listObjects = fake_aws_listObjects_stub;
The problem seems to be returns
, it doesn't execute the function!!
I also cannot write it like this:
fake_aws_listObjects_stub.onCall(0) = fake_aws_truncated;
Because this would be a wrong hand assignment!
What do I have to change? Here are the sinon docs: http://sinonjs.org/docs/
Thanks!!
Upvotes: 0
Views: 645
Reputation: 203231
I would probably go about it another way.
If you want to stub AWS.S3.prototype.listObjects
, I would do that like so:
var stub = sinon.stub(AWS.S3.prototype, 'listObjects');
To call the callback with various values, use stub.yields()
:
stub.onCall(0).yields(null, {
Contents : [{Key: "3fb252ba-0724-438c-93b6-8cd0fd972a8e/image/1:::2.jpg"}],
IsTruncated : true,
NextMarker : "nextMarker"
});
stub.onCall(1).yields(null, {
Contents : [{Key: "3fb252ba-0724-438c-93b6-8cd0fd972a8e/image/2:::3.jpg"}]
});
To test your code, you just call listObjects
like before:
var s3 = new AWS.S3();
s3.listObjects(params, function(err, value) {
...`value` is now one of the fixtures you declared above...
});
To restore to the original version of the method, use one of these:
stub.restore();
// OR:
AWS.S3.prototype.listObjects.restore();
Upvotes: 3