Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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});
}
like image 591
Rakesh Rawat Avatar asked Dec 18 '15 07:12

Rakesh Rawat


1 Answers

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.

like image 194
robertklep Avatar answered Sep 28 '22 06:09

robertklep