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});
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With