最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论