javascript - Sinon JS: Is there a way to stub a method on object argument's key value in sinon js - Stack Overflow

I want to mock a different response on obj.key3 value in following response. Like if obj.key3=true then

I want to mock a different response on obj.key3 value in following response. Like if obj.key3=true then return a different response than if obj.key3=false

function method (obj) {
    return anotherMethod({key1: 'val1', key2: obj.key3});
}

I want to mock a different response on obj.key3 value in following response. Like if obj.key3=true then return a different response than if obj.key3=false

function method (obj) {
    return anotherMethod({key1: 'val1', key2: obj.key3});
}
Share Improve this question edited Dec 18, 2015 at 9:42 robertklep 204k37 gold badges415 silver badges406 bronze badges asked Dec 18, 2015 at 7:17 Rakesh RawatRakesh Rawat 3373 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

You can make a stub return (or do) something based on the argument(s) it's called with using .withArgs() and an object matcher.

For example:

var sinon = require('sinon');

// This is just an example, you can obviously stub existing methods too.
var anotherMethod = sinon.stub();

// Match the first argument against an object that has a property called `key2`,
// and based on its value, return a specific string.
anotherMethod.withArgs(sinon.match({ key2 : true }))  .returns('key2 was true');
anotherMethod.withArgs(sinon.match({ key2 : false })) .returns('key2 was false');

// Your example that will now call the stub.
function method (obj) {
  return anotherMethod({ key1 : 'val1', key2: obj.key3 });
}

// Demo
console.log( method({ key3 : true  }) ); // logs: key2 was true
console.log( method({ key3 : false }) ); // logs: key2 was false

More information on matchers here.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745286824a4620612.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信