Rakesh Rawat
Rakesh Rawat

Reputation: 327

Sinon JS: Is there a way to stub a method on object argument's key value in sinon js

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});
}

Upvotes: 6

Views: 2028

Answers (1)

robertklep
robertklep

Reputation: 203329

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.

Upvotes: 8

Related Questions