Search code examples
javascriptunit-testingsinonsinon-chai

Is it possible to check if a function arguments bound correctly using Sinon.JS


Let say we have a function that returns a function and bounds arguments to it:

function A(x, y){
    return function(x, y){...}.bind(this, x, y);
}

And now we want to know if function A binds arguments correctly:

var resultedFunction = A();
var spy = sinon.spy(resultedFunction);
spy();

The question - is it possible to know if arguments are bound correctly? I've tried this, but it is an empty array

spy.firstCall.args
spy.getCall(0).args

Solution

  • I've finally come to some trick. If the returning function will be not an anonymous then we can spy it and check arguments later:

    var obj = {
      B: function(){
        ...
      },
      A: function(x, y){
        return this.B.bind(this, x, y);
      }
    }
    var x = 1, y = 2;
    var spy = sinon.spy(obj, "B");
    var resultedFunction = obj.A(x, y);
    
    resultedFunction();
    
    expect(spy.firstCall.args[0]).to.equals(x)
    expect(spy.firstCall.args[0]).to.equals(y)