Sinon JS:有没有办法在 sinon js 中对对象参数的键值存根方法
Sinon JS: Is there a way to stub a method on object argument's key value in sinon js
我想在以下响应中模拟对 obj.key3 值的不同响应。就像 if obj.key3=true then return 与 if obj.key3=false
不同的响应
function method (obj) {
return anotherMethod({key1: 'val1', key2: obj.key3});
}
您可以根据使用 .withArgs()
和对象匹配器调用的参数创建存根 return(或执行)某些操作。
例如:
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。
我想在以下响应中模拟对 obj.key3 值的不同响应。就像 if obj.key3=true then return 与 if obj.key3=false
不同的响应function method (obj) {
return anotherMethod({key1: 'val1', key2: obj.key3});
}
您可以根据使用 .withArgs()
和对象匹配器调用的参数创建存根 return(或执行)某些操作。
例如:
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。