Sinon JS: Is there a way to stub a method by the value of the object argument key in sinon js

I want to make fun of another answer for the value of obj.key3 in the next answer. As if obj.key3 = true, then return a different answer than if obj.key3 = false

function method (obj) {
    return anotherMethod({key1: 'val1', key2: obj.key3});
}
+4
source share
1 answer

You can do a stub (or do) something based on the arguments invoked using .withArgs()and matching objects.

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 about matches here .

+4
source

Source: https://habr.com/ru/post/1620688/


All Articles