我希望在以下响应中模拟obj.key3值的不同响应。例如,如果obj.key3=true,则返回与其为false时不同的响应。
function method (obj) {
return anotherMethod({key1: 'val1', key2: obj.key3});
}
function method (obj) {
return anotherMethod({key1: 'val1', key2: obj.key3});
}
.withArgs()
和一个对象匹配器,根据调用它的参数使 stub 返回(或执行)特定结果。
例如: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
关于匹配器(matchers)的更多信息,请点击这里。