Georgi Angelov
Georgi Angelov

Reputation: 4388

How can I get the argument(s) of a stub in sinon and use one of the arguments + other data for the return value of a particular stub call

What I am trying to achieve is to stub a call which will return a certain value. That return value consists of one of the passed parameters and a new value.

How can I grab the argument of a stub and use it to form a return value for a given stub call

E.g.

mockDb.query.onCall(0).return(
   Tuple(this.args(0), "Some other data");
);

I know I can do this:

sinon.stub(obj, "hello", function (a) {
    return a;
});

However, this works on the entire stub and not an individual stub call. Unfortunately, I am not able to provide a different stub for different calls, as I have just one object(the db stub).

Upvotes: 2

Views: 6442

Answers (1)

barnski
barnski

Reputation: 1732

To get access to function parameters on first call on stub you could use:

sinon.stub(obj, "method").onCall(0).callsFake( function(arg) {
    return "data" + arg;
});

This will make first call on stub to return "data" concatenated with passed argument.

I have tested it with node v7.10 and sinon v4. Below whole test script:

const sinon = require('sinon');
let obj = {
    test: (arg1, arg2) => {
        return arg1 + arg2;
    }
}

let stub = sinon.stub(obj, "test");
stub.onCall(0).callsFake((arg1, arg2) => {
    return "STB" + arg1 + arg2;
})


console.log(stub("lol", "lol2")); // -> STBlollol2
console.log(stub("lol", "lol3")); // -> undefined

Upvotes: 6

Related Questions