我想在后面的响应中模拟对obj.key3值的不同响应。就像obj.key3 = true一样,返回与obj.key3 = false
不同的响应function method (obj) {
return anotherMethod({key1: 'val1', key2: obj.key3});
}
答案 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。