Sinon JS:有没有办法在sinon js中对对象参数的键值存根方法

时间:2015-12-18 07:17:35

标签: javascript sinon

我想在后面的响应中模拟对obj.key3值的不同响应。就像obj.key3 = true一样,返回与obj.key3 = false

不同的响应
function method (obj) {
    return anotherMethod({key1: 'val1', key2: obj.key3});
}

1 个答案:

答案 0 :(得分:7)

您可以根据使用.withArgs()和对象匹配器调用的参数来返回(或执行)某些操作。

例如:

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

有关匹配器的更多信息here